Search code examples
jsonkeytraversaljq

Jq: testing a field during walk


Consider following jq config:

walk 
( 
  if (type == "object" and .key | test("something")) then 
    del(.) 
  else 
    . 
  end
)

And following JSON:

[
  {
    "key": "something",
    "value": "something"
  },
  {
    "key": "another thing",
    "value": "another thing"
  },
  {
    "key": "something",
    "value": "something"
  }
]

However, jq throws following error:

jq: error (at :13): boolean (false) cannot be matched, as it is not a string

13 is the last line of the input. What boolean value is it trying to match?


Solution

  • Generally walk() is not required here. I would use map() like this:

    jq 'map(select(.key!="something"))'
    

    About the error you reported, you miss parentheses. It should be:

    jq 'walk(if(type == "object" and (.key | test("something"))) then del(.) else . end)'
                                     ^                        ^