简体   繁体   中英

Get unique nested JSON keys with JQ

How to get the unique keys from attributes key with JQ

{"id":1, "attributes":{"a": 1, "b": 2, "c": 3}}
{"id":2, "attributes":{"a": 4, "b": 5, "d": 6}}
{"id":3, "name":"ABC"}

Result like this [ "a", "b", "c", "d" ]

I'm try like this

jq '.attributes' test.json | jq -r '[inputs | keys[]] | unique | sort'

or

jq -r '[inputs.attributes | keys[]] | unique | sort' test.json

but getting error

jq: error (at:11): null (null) has no keys

One way could be using reduce on subsequent inputs :

jq 'reduce inputs.attributes as $a (.attributes; . + $a) | keys'
[
  "a",
  "b",
  "c",
  "d"
]

Demo

Along the lines of your second attempt:

jq -n '[inputs.attributes // empty | keys_unsorted[]] | unique'

The important point is that we have to take care of the case where there is no "attributes" key.

Note also that unique sorts, so (unless you're using gojq) we can use keys_unsorted to avoid redundant sorting.

With slurp:

jq -s 'map(.attributes|keys?)|add|unique' test.json

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