我在文本檔案中有以下 Json 輸入json.txt:
{
"files":[
{
"id":49894894,
"list":[
{
"name":"one",
"animal_potato_carrot":{
"options":[
{
"id":4989,
"url":"https://example.com/text.txt"
},
{
"id":3994,
"url":"https://example.com/randomfile.json"
}
]
}
},
{
"name":"two",
"cat_dog_rabbit":[
{
"id":4989,
"url":"https://example.com/text2.txt"
},
{
"id":3994,
"url":"https://example.com/randomfile.json"
}
]
},
{
"name":"three",
"animal_potato_carrot":{
"options":[
{
"id":4989,
"url":"https://example.com/text3.txt"
},
{
"id":3994,
"url":"https://example.com/randomfile.json"
}
]
}
}
]
}
]
}
我只想獲取options每個標簽animal_potato_carrot或cat_dog_rabbit嵌套標簽串列中的第一個 url(注意它們具有不同的結構)
所以我的輸出將是這些塊中的前三個 url:
["https://example.com/text.txt", "https://example.com/text2.txt, "https://example.com/text3.txt"]
我試過jq json.txt -c '.. |."animal_potato_carrot"? | select(. != null)'了,但這會回傳體內的所有東西,而不僅僅是第一個 url。
編輯:
這兩個命令分別回傳 url,animal_potato_carrot但是cat_dog_rabbit有沒有辦法組合這些命令?
jq -c '[..|.animal_potato_carrot?|select(. != null)|.options[0].url]' json.txt
jq -c '[..|.cat_dog_rabbit?|select(. != null)|.[0].url]' json.txt
uj5u.com熱心網友回復:
如果要連接兩個陣列,可以使用 運算子:
jq -c '[..|.animal_potato_carrot?|select(. != null)|.options[0].url] [..|.cat_dog_rabbit?|select(. != null)|.[0].url]' json.txt
請注意,結果中的專案順序與您要求的不完全一致,因為首先animal_potato_carrot確定所有 -url,然后確定所有cat_dog_rabbit-url。
結合使用兩個過濾器,可能最符合您的需求:
jq -c '[..|(.animal_potato_carrot?.options),(.cat_dog_rabbit?)|.[0].url|select(. != null)]' json.txt
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/461371.html
