[英]Flatten a hierarchical JSON array using JQ
Can anyone help me get the correct jq command to flatten the below example?谁能帮我获得正确的 jq 命令来展平下面的示例? I've seen a few other posts and I'm hacking away at it but can't seem to get it.我看过其他一些帖子,我正在破解它,但似乎无法得到它。 I'd greatly appreciate any help.我将不胜感激任何帮助。
Input:输入:
[
{
"name": "level1",
"children": [
{
"name": "level2",
"children": [
{
"name": "level3-1",
"children": []
},
{
"name": "level3-2",
"children": []
}
]
}
]
}
]
Output: Output:
[
{
"displayName": "level1",
"parent": ""
},
{
"displayName": "level2",
"parent": "level1"
},
{
"displayName": "level3-1",
"parent": "level2"
},
{
"displayName": "level3-2",
"parent": "level2"
}
]
With a simple recursive function:使用简单的递归 function:
def f: .name as $parent | .children[] | {$parent, displayName: .name}, f;
[ {name: "", children: .} | f ]
Here's a straightforward solution that does not involve a helper function and actually solves a more general problem.这是一个不涉及帮助程序 function 的简单解决方案,实际上解决了一个更普遍的问题。 It is based on the idea of beginning by adding a "parent" key to each child, and then using ..
to collect all the name/parent pairs.它基于首先为每个孩子添加一个“父”键,然后使用..
来收集所有名称/父对的想法。
So first consider:所以首先考虑:
[ walk(if type=="object" and has("children")
then .name as $n | .children |= map(.parent = $n)
else . end)
| ..
| select(type=="object" and has("name"))
| {displayName: .name, parent}
]
This meets the requirements except that for the top-level (parentless) object, it produces a.parent value of null
.除了顶级(无父) object 之外,这符合要求,它产生的 a.parent 值为null
。 That would generally be more JSON-esque than "", but if the empty string is really required, one has simply to replace the last non-trivial line above by:这通常比“”更具有 JSON 风格,但如果确实需要空字符串,则只需将上面的最后一行替换为:
| {displayName: .name, parent: (.parent // "")}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.