'flatten and filter a tree json object using jq
How can I filter and flatten a tree-like json object using jq so that it's only applied to leaves of the tree? In the example below I'd like jq to return something like [{"name": "foo1"}, {"name": "bar"}]
obj = {
"name": "root",
"nodes": [
{"name": "foo1"},
{"name": "foo2", nodes = [
{"name": "bar"}
]}
]
}
Solution 1:[1]
[ recurse(.nodes[]?) | select(has("nodes")|not) ]
This walks the tree and retains all nodes that do not have a nodes key themselves.
Solution 2:[2]
demo https://jqplay.org/s/Xrgqos4W-M
filter:
[recurse(.nodes[]?) | select(has("nodes") | not) | {name:.name}]
input:
{
"name": "root",
"nodes": [
{"name": "foo1"},
{"name": "foo2",
"nodes": [
{"name": "bar"}
]}
]
}
ouput:
[{"name":"foo1"},{"name":"bar"}]
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 | Botje |
| Solution 2 | Logan Lee |
