【发布时间】:2020-03-07 14:56:41
【问题描述】:
鉴于以下 JSON,
我正在尝试过滤汽车数组中的项目,其中项目的 cmets 数组为空:
.cars[] | select(.comments == null)
或者项目的 cmets 数组存在并且任何 cmets 对象不包含值“FooBar”
.cars[] | select( select(.comments != null) | (any(.comments[]; index("FooBar")) | not) )
同时保留原始结构。
使用 jq,我可以弄清楚如何创建我想要过滤的标准,但我无法理解如何将其应用于顶级项目。
JSON 输入:
{
"person": {
"first_name": "Bob",
"last_name": "Smith"
},
"addresses": [
{
"home": {
"line1": "123",
"line2": "A st."
}
},
{
"work": {
"line1": "456",
"line2": "B st."
}
}
],
"cars": [
{
"make": "Honda",
"model": "Civic"
},
{
"make": "Honda",
"model": "Accord"
},
{
"make": "Honda",
"model": "Pilot",
"comments": [
"Comment 1",
"Comment 2",
"FooBar"
]
},
{
"make": "Honda",
"model": "Passport",
"comments": [
"Comment 3",
"Comment 4"
]
}
]
}
JSON 输出,与输入相同,但注释数组中包含值“FooBar”的对象被过滤掉:
{
"person": {
"first_name": "Bob",
"last_name": "Smith"
},
"addresses": [
{
"home": {
"line1": "123",
"line2": "A st."
}
},
{
"work": {
"line1": "456",
"line2": "B st."
}
}
],
"cars": [
{
"make": "Honda",
"model": "Civic"
},
{
"make": "Honda",
"model": "Accord"
},
{
"make": "Honda",
"model": "Passport",
"comments": [
"Comment 3",
"Comment 4"
]
}
]
}
【问题讨论】: