我有一个JSON结构,它有一个对象数组。
{
"payload": {
"location": {
"uid": 1,
"type": "foo"
},
"name": "foo",
"maxResults": 10
},
"product": {
"uid": "1232323",
"source": "foo",
"service": "pricing",
"version": "0.1",
"time": 1507602150899,
"type": "mobile",
"id": 1
}
}
{
"payload": {
"location": {
"uid": 2,
"type": "bar"
},
"name": "bar",
"maxResults": 10
},
"product": {
"uid": "244434242",
"source": "bar",
"service": "pricing",
"version": "0.2",
"time": "1507602ds0899",
"type": "phone",
"id": 2
}
}
我想根据条件过滤对象,其中product.type == mobile
然后在匹配的对象中,我只想要id
和service
字段。所以在上面的例子中,下面是O / P.
{
"service" : "pricing",
"id" : 1
}
我可以使用
提取匹配的对象cat myjson.json | jq 'select(.product.type == "moble")'
但之后如何只过滤对象的service
和id
字段?
答案 0 :(得分:1)
也许这会对你有所帮助:
map(select(.product.type == "mobile")) | .[] | {id: .product.id, service: .product.service}
答案 1 :(得分:0)
问题中当前显示的数据不是严格的JSON,但由于OP提到输入应该是一个数组,下面假设数据是对象的JSON数组。
然后是一个简洁的解决方案:
data[] | .product | select(.type == "mobile") | {service, id}
如上所述调整输入数据,输出如下所示,即:
{"service":"pricing","id":1}