【问题标题】:Merging two JSON arrays using jq使用 jq 合并两个 JSON 数组
【发布时间】:2019-10-12 06:39:25
【问题描述】:

我想加入数组 '.fileStats' 和 '.files' 以便只有一个数组。

初始 JSON:

{"arguments":{"torrents":[{"fileStats":[{"bytesCompleted":0,"priority":0,"wanted":false},{"bytesCompleted":0,"priority":0,"wanted":true},{"bytesCompleted":0,"priority":0,"wanted":true}],"files":[{"bytesCompleted":0,"length":30,"name":"1.txt"},{"bytesCompleted":0,"length":99,"name":"2.exe"},{"bytesCompleted":0,"length":4833317512,"name":"3.iso"}]}]},"result":"success"}

数组合并后的对象示例:

{
  "bytesCompleted": 0,
  "length": 30,
  "name": "1.txt",
  "priority": 0,
  "wanted": true
}

我通过“扁平化”采用了不同的方法:

.arguments.torrents[] | map(to_entries) | flatten | group_by(.key)

但是能够基于“.wanted”是真/假来选择对象,然后检索“.name”是更可取的。

【问题讨论】:

    标签: json jq


    【解决方案1】:
    jq '.arguments.torrents[] | range(.fileStats|length) as $i| select(.fileStats[$i].wanted)| .fileStats[$i]+.files[$i]'
    

    我认为上面的代码可以满足您的需求。它会根据您的输入提供以下输出。

    {
      "bytesCompleted": 0,
      "priority": 0,
      "wanted": true,
      "length": 99,
      "name": "2.exe"
    }
    {
      "bytesCompleted": 0,
      "priority": 0,
      "wanted": true,
      "length": 4833317512,
      "name": "3.iso"
    }
    

    更多细节请查阅jq手册中的“变量”、“范围”、“长度”、“选择”和“合并”。 https://stedolan.github.io/jq/manual/

    【讨论】:

      猜你喜欢
      • 2018-10-25
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多