使用JQ在树状json对象中沿每个路径收集所有从根到叶的值

时间:2018-12-20 07:20:03

标签: json path jq scalar

使用JQ在树状json对象中沿每个路径收集所有从根到叶的值。使用走动或展平功能似乎应该很容易,但是尽管已经提出了一些有用的问题,但我无法弄清楚。

我有这个

 {
     "cond1":["a","b","c"],
     "cond2":["a1","b2","c"],
     "cond2":["a","b","c3"]    
 }    

我想要这个

["cond1","a"]
["cond1","b"]
["cond1","c"]
["cond2","a1"]
["cond2","b2"]
["cond2","c"]
["cond2":"a"]
["cond2":"b"]
["cond2":"c3"]

类似的问题: https://github.com/stedolan/jq/issues/646 jq - How do I print a parent value of an object when I am already deep into the object's children?

此外,如果数组不是由[“ a”,“ b”,“ c”]而是由嵌套对象(即[[“ x2”,“ x3”],[“ x1,” x2“]]

1 个答案:

答案 0 :(得分:2)

回答两个问题的关键是paths。 例如,以下过滤器在第一种情况下会产生所需的输出:

paths as $p
| getpath($p)
| select(scalars)
| ($p | map(select(type=="string"))) + [.]

同一过滤器可与任何有效JSON一起用作输入。沿着Q中所示的行用有效的嵌套数组替换.cond2,输出将是:

["cond1","a"]
["cond1","b"]
["cond1","c"]
["cond2","x2"]
["cond2","x3"]
["cond2","x1"]
["cond2","x2"]