[英]How to filter a JSON object based on a condition and then just select few keys from the filtered object using the JQ parser
我有一個下面的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
字段?
也許這會幫助您:
map(select(.product.type == "mobile")) | .[] | {id: .product.id, service: .product.service}
問題中當前顯示的數據嚴格來說不是JSON,但是由於OP提到輸入應該是數組,因此以下假設該數據是對象的JSON數組。
簡潔的解決方案是:
data[] | .product | select(.type == "mobile") | {service, id}
通過如上所述調整輸入數據,輸出將如圖所示,即:
{"service":"pricing","id":1}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.