jsonjqsafe-browsing

jq - can't extract key values from google safebrowsing json response


So I've read the jq tutorial and played with the github json responses from there and extracted some values of some other keys so I think I understand how the syntax works. Unfortunately nothing works when attempting to use it on a Google safe-browsing json response. Here is the full response stored in a variable (did the same for the github examples from jq tutorial):

echo "$safeb"
{
  "matches": [
{
  "threatType": "MALWARE",
  "platformType": "ALL_PLATFORMS",
  "threat": {
    "url": "http://www.wittyvideos.com"
  },
  "cacheDuration": "300s",
  "threatEntryType": "URL"
  }
 ]
}

... and this is what I tried:

echo "$safeb" | jq '.matches.threatType'
jq: error (at <stdin>:13): Cannot index array with string "threatType"

echo "$safeb" | jq '.threatType'
null

echo "$safeb" | jq '.[] | .threatType'
jq: error (at <stdin>:13): Cannot index array with string "threatType"

echo "$safeb" | jq '.[] | {type: .threatType}'
jq: error (at <stdin>:13): Cannot index array with string "threatType"

Thanks in advance.


Solution

  • .matches.threatType

    .matches is an array, so you'd have to use [] to expand it, e.g.:

    .matches[].threatType
    

    .threatType

    This attempt could be salvaged using .., e.g.

    .. | .threatType? // empty
    

    .[] | .threatType

    No comment :-)

    .[] | {type: .threatType}

    You probably meant:

    .matches[] | {type: .threatType}
    

    p.s.

    You might want to use debug to help debug/understand what's going on.

    Also, in future, please don't forget to describe or show the expected output.