Home > Blockchain >  filter keys in JSON using jq
filter keys in JSON using jq

Time:11-15

I am having a complex nested json

{
...
"key1": {
   "key2" : [
       { ...
         "base_score" :4.5
       }
    ]
"key3": {

       "key4": [
         { ...
           "base_score" : 0.5 
           ...
         }
       ]

       }
...

    }
}

There maybe multiple "base_score" in the json("base_score" path is unknown) and the corresponding value will be a number, I have to check if at least one such value is greater than some known value 7.0, and if there is, I have to do "exit 1". I have to write this query in shell script.

CodePudding user response:

Assuming the input is valid JSON in a file named input.json, then based on my understanding of the requirements, you could go with:

jq --argjson limit 7.0 '
  any(.. | select(type=="object" and (.base_score|type=="number")) | .base_score; . > $limit)
  | halt_error(if . then 1 else 0 end)
' input.json

You can modify the argument to halt_error to set the exit code as you wish.

Note that halt_error redirects its input to stderr, so you might want to append 2> /dev/null (or the equivalent expression appropriate for your shell) to the above invocation.

CodePudding user response:

You can easily get a stream of base_score values at any level and use that with any:

any(..|.base_score?; . > 7)

The stream will contain null values for objects without the property, but null is not greater than any number, so that shouldn't be a stopper.

You could then compare the output or specify -e/--exit-status to be used with a condition directly:

jq -e 'any(..|.base_score?; . > 7)' >/dev/null && exit 1
  • Related