2015-09-12 70 views
-1

這裏是我的輸入JSON:JQ:ID而不是數字的輸出值​​

{ 
    "channels": [ 
     { "id": 1, "name": "Pop"}, 
     { "id": 2, "name": "Rock"} 
    ], 
    "links": [ 
     { "id": 2, "streams": [ {"url": "http://example.com/rock"} ] }, 
     { "id": 1, "streams": [ {"url": "http://example.com/pop"} ] }   
    ] 
} 

這是我想作爲輸出:

"http://example.com/pop" 
"Pop" 
"http://example.com/rock" 
"Rock" 

所以我需要JQ基於與.links[].streams[0].url更換.channels[].id.links[].id

我不知道它是否正確,但這是我如何設法輸出的網址:

(.channels[].id | tostring) as $ids | [.links[]] | map({(.id | tostring): .streams[0].url}) | add as $urls | $urls[$ids] 

"http://example.com/pop" 
"http://example.com/rock" 

問題是,我該如何將.channels[].name添加到它?

回答

0

有時候你必須要小心,你問什麼,但這樣會產生的結果,你說你想要的:

給定的輸入
.channels[] as $channel 
| $channel.name, 
    (.links[] | select(.id == $channel.id) | .streams[0].url) 

輸出:

"Pop" 
"http://example.com/pop" 
"Rock" 
"http://example.com/rock" 
0

這裏是一個解決方案其使用減少setpath.links製作$urls查找表,然後掃描.channels生成相應的url和名字。

(
    reduce .links[] as $l (
     {}; 
     setpath([ $l.id|tostring ]; [$l.streams[].url]) 
    ) 
) as $urls 
| .channels[] 
| $urls[ .id|tostring ][], .name 

如果多個URL,目前在「流」屬性打印名字之前,這將 全部打印出來。例如如果輸入是

{ 
    "channels": [ 
     { "id": 1, "name": "Pop"}, 
     { "id": 2, "name": "Rock"} 
    ], 
    "links": [ 
     { "id": 2, "streams": [ {"url": "http://example.com/rock"}, 
           {"url": "http://example.com/hardrock"} ] }, 
     { "id": 1, "streams": [ {"url": "http://example.com/pop"} ] }   
    ] 
} 

的輸出將是

"http://example.com/pop" 
"Pop" 
"http://example.com/rock" 
"http://example.com/hardrock" 
"Rock" 
相關問題