Json
jq - 在一行中列印值
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)
任何解決方法表示讚賞。
使用“加入”,
-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: -
$ jq -r '.[] | [ "name:", .name ], [ "groups:", .grp[].name ] | @tsv' file.json name: cust1 groups: BA2 GA1 NA1 TR3 TS1
也就是說,給出
@tsv
兩個數組,一個帶有名稱,一個帶有組。每個數組將成為自己的行。如果
grp
數組可能為空,而您想插入 a-
代替:$ jq -r '.[] | [ "name:", .name ], [ "groups:", (.grp // [])[].name // "-" ] | @tsv' file.json name: cust1 groups: -
操作
x // y
返回x
,除非x
計算結果為null
或false
在這種情況下返回y
。這也將處理
grp
完全失去的情況(不僅僅是一個空數組)。