这里的jq新手,尝试使用jq过滤嵌套的json。
{
"data": {
"products": [
{
"id": "1",
"title": "item01",
"description": "item01 description",
"skus": [
{
"color": "blue",
"precision": 2,
"details": {
"longDescription": "This a long description with a keywordA"
}
},
{
"color": "green",
"precision": 1,
"details": {
"longDescription": ""
}
}
]
},
{
"id": "2",
"title": "item02",
"description": "item02 description",
"skus": [
{
"color": "red",
"precision": 2,
"details": {
"longDescription": ""
}
},
{
"color": "yellow",
"precision": 1,
"details": {
"longDescription": ""
}
}
]
}
]
}
}
所需的输出:
{
"title": "item01",
"color": "blue",
"longDescription": "This a long description with a keywordA"
}
我能够获得标题和描述jq '.data.products[] | {title: .title, longDescription: .skus[].details.longDescription } | select(.longDescription | contains("keywordA") )'
结果:
{
"title": "item01",
"longDescription": "This a long description with a keywordA"
}
但是,如果我在过滤器中包含颜色,则会得到不正确的数据。
jq '.data.products[] | {title: .title, color:.skus[].color, longDescription: .skus[].details.longDescription } | select(.longDescription | contains("keywordA") )'
{
"title": "item01",
"color": "blue",
"longDescription": "This a long description with a keywordA"
}
{
"title": "item01",
"color": "green",
"longDescription": "This a long description with a keywordA"
}
答案 0 :(得分:1)
有很多可能性,但是以下使用“生成并测试”方法的过滤器确实产生了预期的结果并说明了一些可能的技术:
.data.products[]
| {title} + (.skus[] | {color} + (.details | {longDescription}))
| select(.longDescription | contains("keywordA"))