jq:ids 的输出值而不是数字

jq: output values of ids instead of numbers

这是我的输入 json:

{
    "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[].id

.channels[].id换成.links[].streams[0].url

不知道对不对,我是这样输出url的:

(.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

有时你需要小心你所要求的,但这会产生你说你想要的结果:

.channels[] as $channel
| $channel.name,
  (.links[] | select(.id == $channel.id) | .streams[0].url) 

给定输入的输出:

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

这是一个解决方案,它使用 reducesetpath$urls 查找 table =14=] 然后扫描 .channels 生成相应的 url 和名称。

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

如果 "streams" 属性中存在多个 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"