[英]How do I use jq to flatten a complex json structure?
I have the following simplified json structure: Notice an array of values, which have children, whose children could have children.我有以下简化的 json 结构:注意一个值数组,其中有孩子,其孩子可能有孩子。
{
"value": [
{
"id": "12",
"text": "Beverages",
"state": "closed",
"attributes": null,
"iconCls": null
},
{
"id": "10",
"text": "Foods",
"state": "closed",
"attributes": null,
"iconCls": null,
"children": [
{
"id": "33",
"text": "Mexican",
"state": "closed",
"attributes": null,
"iconCls": null,
"children": [
{
"id": "6100",
"text": "Taco",
"count": "3",
"attributes": null,
"iconCls": ""
}
]
}
]
}
]
}
How do I flatten a json structure using jq?如何使用 jq 展平 json 结构? I would like to print each element just once, but in a flat structure.
我想只打印一次每个元素,但要采用扁平结构。 An example output:
示例 output:
{
"id": "12",
"category": "Beverages"
},
{
"id": "10",
"category": "Foods"
},
{
"id": "33",
"category": "Mexican"
},
{
"id": "6100",
"category": "Tacos"
}
My attempt doesn't seem to work at all:我的尝试似乎根本不起作用:
cat simple.json - | jq '.value[] | {id: .id, category: .text} + {id: .children[]?.id, category: .children[]?.text}'
..
is your friend: ..
是你的朋友:
.. | objects | select( .id and .text) | {id, category: .text}
If your actual input is that simple, recursively extracting id and text from each object under value should work.如果您的实际输入如此简单,那么从value下的每个 object 递归提取id和text应该可以工作。
[ .value | recurse | objects | {id, category: .text} ]
I was totally going in the wrong direction
我完全走错了方向
Not really.并不真地。 Going in that direction, you would have something like:
朝着那个方向前进,你会得到类似的东西:
.value[]
| recurse(.children[]?)
| {id, category: .text}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.