简体   繁体   English

使用 JQ 获取唯一的嵌套 JSON 密钥

[英]Get unique nested JSON keys with JQ

How to get the unique keys from attributes key with JQ如何使用 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" ]像这样的结果 [ "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 jq: 错误 (at:11): null (null) has no keys

One way could be using reduce on subsequent inputs :一种方法是在后续inputs上使用reduce

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.还要注意unique排序,所以(除非你使用 gojq)我们可以使用keys_unsorted来避免冗余排序。

With slurp:啜饮:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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