![jq:如何为每个子对象值打印一行,用子对象值重复顶级值](https://linux22.com/image/12597/jq%EF%BC%9A%E5%A6%82%E4%BD%95%E4%B8%BA%E6%AF%8F%E4%B8%AA%E5%AD%90%E5%AF%B9%E8%B1%A1%E5%80%BC%E6%89%93%E5%8D%B0%E4%B8%80%E8%A1%8C%EF%BC%8C%E7%94%A8%E5%AD%90%E5%AF%B9%E8%B1%A1%E5%80%BC%E9%87%8D%E5%A4%8D%E9%A1%B6%E7%BA%A7%E5%80%BC.png)
我试图仅打印 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
之前记住的。