简体   繁体   中英

Filter keys of the objects in a deeply nested JSON with jq

Given the following input

[
  {
    "k1":[{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6}],
    "k2":[{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6}]
  }
]

how should I proceed to obtain the following output?

[
  {
    "k1":[{"a":1,"b":2}],
    "k2":[{"a":1,"b":2}]
  }
]

ie I have some objects deeply in the JSON, and I want to remove all keys in those nested objects except "a" and "b" , and keep the original JSON structure.

Note however that the original object might have dozens of keys, I only want to keep 2 or 3 of them.

For simple top-level operations I was able to select subsets of objects with {a:.a, b:.b} or {a,b} syntax, but in the nested context I don't know how to proceed and preserve the JSON structure.

In general, what is the best attitude to do operations on a deeply nested level, without altering the parent levels?

In brief, walk is your friend.

(If it is not available in your jq, simply include its def in your jq program; the def can easily be found by googling: jq def walk)

Some variation of the following should solve the immediate problem:

walk( if type == "object" then {a,b} else . end )

You can use |= operator to do what you want on nested levels.

There is also a fairly simple function you can use to pick specific paths out of json objects.

This stackoverflow.com thread has a more in-depth explanation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM