我试图仅打印 json 中的某些值(每个子对象一行),并在每一行上重复顶部对象中的一个值。
输入示例:
[
{
"name": "level1Name",
"lv1id": "id1",
"requests": [
{
"lv2id": "id2",
"name": "lvl2requestA",
"startDate": "2019-02-05 08:52:33.663+0000",
"requestState": "Succeeded"
},
{
"lv2id": "id2",
"name": "lvl2requestB",
"startDate": "2019-02-05 08:52:33.421+0000",
"requestState": "Succeeded"
}
]
},
{
"name": "level1Name",
"lv1id": "id12",
"requests": [
{
"lv2id": "id2",
"name": "lvl2requestD",
"startDate": "2019-02-05 08:52:19.823+0000",
"requestState": "Succeeded"
},
{
"lv2id": "id2",
"name": "lvl2requestA",
"startDate": "2019-02-05 08:52:19.689+0000",
"requestState": "Succeeded"
}
]
}
]
目标输出
["id1","2019-02-05 08:52:33.663+0000","lvl2requestA","Succeeded"]
["id1","2019-02-05 08:52:33.421+0000","lvl2requestB","Succeeded"]
["id12","2019-02-05 08:52:19.823+0000","lvl2requestD","Succeeded"]
["id12","2019-02-05 08:52:19.689+0000","lvl2requestA","Succeeded"]
我已经尝试了几次尝试(例如使用变量/符号绑定运算符)。欢迎任何线索。
答案1
$ jq -c '.[] | .lv1id as $id | .requests[] | [$id, .startDate, .name, .requestState]' file.json
["id1","2019-02-05 08:52:33.663+0000","lvl2requestA","Succeeded"]
["id1","2019-02-05 08:52:33.421+0000","lvl2requestB","Succeeded"]
["id12","2019-02-05 08:52:19.823+0000","lvl2requestD","Succeeded"]
["id12","2019-02-05 08:52:19.689+0000","lvl2requestA","Succeeded"]
这获取最顶层数组 ( .[]
) 的每个元素并将该元素分配.lv1id
给$id
。然后它迭代.requests[]
该元素的数组并为每个元素构造输出数组它是由您似乎需要的各个部分组成的元素,包括$id
之前记住的。