【问题标题】:jq: output values of ids instead of numbersjq:输出 ids 的值而不是数字
【发布时间】:2015-09-12 03:53:41
【问题描述】:

这是我的输入 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

我不知道这是否正确,但这就是我设法输出网址的方式:

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

【问题讨论】:

    标签: json jq


    【解决方案1】:

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

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

    给定输入的输出:

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

    【讨论】:

      【解决方案2】:

      这是一个解决方案,它使用 reducesetpath.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"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-06
        • 1970-01-01
        • 2011-03-13
        • 2020-06-20
        相关资源
        最近更新 更多