Home > Enterprise >  getting array elements missing a key with jq
getting array elements missing a key with jq

Time:04-28

I have the following json array

[
{
"k1":"n1",
"k2":[
      {"a1":"v1",
       "a2":[{"b1":"v11"},...],
        "a3":"v3",...},
       {"a1":"v12",
        "a3":"v32",...},
       
     ],
     ...
},
{
"k1":"n2",
 "k2":[
      {"a1":"v1",
        "a3":"v3",...}
     ],
...
},
{
"k1":"n2",
 "k3":[
      {"s1":"v1",
        "s3":"v3",...},
      ...
   ]
},
...
]

I would like to use jq to get all the elements where the key k2 exists and just return the array elements of k2 that dont have the subkey "a2". So for the example above I would like to return

[
{
"k1":"n1",
"k2":[         
       {"a1":"v12",
        "a3":"v32",...},
       
     ],
},
...
]

(in the first element, only the first element of k2 has the subkey a2 so thats the only one I removed, the 2nd element has k2 but k2 doesnt have any elements with a2 and the 3rd element doesnt have k2)

CodePudding user response:

Filter using select and has, adjust the output using map.

jq 'map(
  select(has("k2") and any(.k2[]; has("a2")))
  | .k2 |= map(select(has("a2") | not))
)'
[
  {
    "k1": "n1",
    "k2": [
      {
        "a1": "v12",
        "a3": "v32"
      }
    ]
  }
]

Demo

  • Related