Home > front end >  selecting json entries that dont contain subkey
selecting json entries that dont contain subkey

Time:04-27

I am new to jq. I have a json file that looks like this

[
{
"k1":"a",
"k2":"aa",
"k3":["sk1":"a","sk2":"cc","sk3":"cc"],
"k4":["sk6":"zs","sk8":"we",...],
...
},
{
"k1":"b",
"k2":"ba",
"k3":["sk1":"a","sk3":"cc",...],
"k4":["sk6":"zs","sk8":"we",...],
...
},
{
"k1":"b",
"k2":"ba",
"k4":["sk6":"zs","sk8":"we",...],
...
}
...
]

I would like to get all the entries in the array such that the key 3 ("k3") doesnt have the subkey "sk2". Note that some of the elements of the array dont have "k3" (so I would like to remove those) and then those that have "k3" sometimes dont have "sk2" (thats the ones I want).

How to accomplish this in jq?

CodePudding user response:

You can use select to filter, and has to check the keys:

jq 'map(select(has("k3") and (.k3 | has("sk2") | not)))' file.json
[
  {
    "k1": "b",
    "k2": "ba",
    "k3": {
      "sk1": "a",
      "sk3": "cc"
    },
    "k4": {
      "sk6": "zs",
      "sk8": "we"
    }
  }
]

Demo

  • Related