'How to extract all (also nested) key names with jq
How can I extract all key names, even in nested objects with jq? For example, I have json:
{
"a": 1,
"b": {
"c": 2
}
}
and I want to get list: a, b, b.c
I know that for top level keys I can get this, with:
. | to_entries[] | .key
, but what about keys in nested objects?
Solution 1:[1]
Short jq solution:
jq -r '[paths | join(".")]' jsonfile
The output:
[
"a",
"b",
"b.c"
]
paths
function outputs the paths to all the elements in its inputjoin(".")
- to concatenate keys within hierarchical paths
Solution 2:[2]
Given input foo.json
{"a":1,"b":[{"c":2}]}
jq '[
paths |
map(select(type!="number")) |
select(length > 0) |
join(".")
] | unique' foo.json
outputs
[
"a",
"b",
"b.c"
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | CervEd |