json 输入:
[
{
"name": "cust1",
"grp": [
{
"id": "46",
"name": "BA2"
},
{
"id": "36",
"name": "GA1"
},
{
"id": "47",
"name": "NA1"
},
{
"id": "37",
"name": "TR3"
},
{
"id": "38",
"name": "TS1"
}
]
}
]
预期输出有两行:
name: cust1
groups: BA2 GA1 NA1 TR3 TS1
我试图构建过滤器但没有成功..
$ jq -r '.[]|"name:", .name, "groups:", (.grp[]|[.name]|@tsv)' test_json
name:
cust1
groups:
BA2
GA1
NA1
TR3
TS1
更新:下面提供的解决方案工作正常,但我没有预测不存在组时的情况:
[
{
"name": "cust1",
"grp": null
}
]
在这种情况下,提供的解决方案返回错误:
$ jq -jr '.[]|"name:", " ",.name, "\n","groups:", (.grp[]|" ",.name),"\n"' test_json2
name: cust1
jq: error (at test_json2:6): Cannot iterate over null (null)
任何解决方法表示赞赏。
答案1
使用“加入”,-j
$ jq -jr '.[]|"name:", " ",.name, "\n","groups:", (.grp[]|" ",.name),"\n"' test_json
name: cust1
groups: BA2 GA1 NA1 TR3 TS1
并带有占位符
$ jq -jr '.[]|"name:", " ",.name, "\n","groups:", (.grp//[{"name":"-"}]|.[]|" ",.name),"\n"' test_json
name: cust1
groups: -
答案2
$ jq -r '.[] |
[ "name:", .name ], [ "groups:", .grp[].name ]
| @tsv' file.json
name: cust1
groups: BA2 GA1 NA1 TR3 TS1
也就是说,给出@tsv
两个数组,一个包含名称,一个包含组。每个数组将成为其自己的行。
如果grp
数组可能为空而您想插入一个-
:
$ jq -r '.[] |
[ "name:", .name ], [ "groups:", (.grp // [])[].name // "-" ]
| @tsv' file.json
name: cust1
groups: -
除非计算结果为或 ,否则该操作x // y
将返回,在这种情况下它会返回。x
x
null
false
y
这也将处理完全缺失的情况grp
(不仅仅是空数组)。