json - jq - 合并两个 JSON 文件时出错 "cannot be multiplied"

标签 json jq

我有两个包含一些 JSON 的文件。

File1 - 有些值可以是字符串,有些可能是 null,VolumeId 始终设置。

[
  {
    "VolumeId": "vol-xxxxxxx1",
    "Tag1": "Tag1Value",
    "Tag2": "Tag2Value",
    "Tag3": "Tag3Value",
    "Tag4": "Tag4Value",
    "Tag5": "Tag5Value",
    "Tag6": "Tag6Value"
  },
  {
    "VolumeId": "vol-xxxxxxx2",
    "Tag1": "Tag1Value",
    "Tag2": "null",
    "Tag3": "null",
    "Tag4": "Tag4Value",
    "Tag5": "null",
    "Tag6": "Tag6Value"
  },
  {
    "VolumeId": "vol-xxxxxxx3",
    "Tag1": "null",
    "Tag2": "null",
    "Tag3": "null",
    "Tag4": "null",
    "Tag5": "null",
    "Tag6": "null"
  }
]

File2 - VolumeId 将始终与 File1 中的那些相匹配,并且 Tag7 可能为也可能不为空。
[
  {
    "VolumeId": "vol-xxxxxxx1",
    "Tag7": "Tag7Value"
  },
  {
    "VolumeId": "vol-xxxxxxx2",
    "Tag7": "Tag7Value"
  },
  {
    "VolumeId": "vol-xxxxxxx3",
    "Tag7": "null"
  }
]

我需要将这些组合成一个 JSON 数组:
[
  {
    "VolumeId": "vol-xxxxxxx1",
    "Tag1": "Tag1Value",
    "Tag2": "Tag2Value",
    "Tag3": "Tag3Value",
    "Tag4": "Tag4Value",
    "Tag5": "Tag5Value",
    "Tag6": "Tag6Value",
    "Tag7": "Tag7Value"
  },
  {
    "VolumeId": "vol-xxxxxxx2",
    "Tag1": "Tag1Value",
    "Tag2": "null",
    "Tag3": "null",
    "Tag4": "Tag4Value",
    "Tag5": "null",
    "Tag6": "Tag6Value",
    "Tag7": "Tag7Value"
  },
  {
    "VolumeId": "vol-xxxxxxx3",
    "Tag1": "null",
    "Tag2": "null",
    "Tag3": "null",
    "Tag4": "null",
    "Tag5": "null",
    "Tag6": "null",
    "Tag7": "null"
  }
]

尝试使用以下命令时出现错误:
jq -s '.[0] * .[1]' /path/to/file1 /path/to/file2
array ([{"VolumeId...) and array ([{"VolumeId...) cannot be multiplied

任何帮助表示赞赏。

最佳答案

我假设您想将所有具有相同 .VolumeId 的条目合并为一个。为此,首先我们将对象数组的数组 flatten 编码为对象数组。然后,我们 group_by(.VolumeId) 。最后,我们对每个组进行 map,并通过计算其所有元素的乘积对其进行 reduce。最终结果如下所示:

jq -s 'flatten | group_by(.VolumeId) | map(reduce .[] as $x ({}; . * $x))' /path/to/file1 /path/to/file2

关于json - jq - 合并两个 JSON 文件时出错 "cannot be multiplied",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36880891/

相关文章:

python - 在 Flask 中获取数据 JSON

javascript - 将带有 json 对象的 .js 文件中的数据导入到 mysql 数据库

json - 使用 jq 连接和过滤 JSON 文件

syntax - 如何使用jq查询数字子键的值

json - 统计属性为 "null"或包含 "null"的对象数量

c# - JSON 映射到 C# 类

json - 如何配置extjs阅读器来读取这个json?

json - 在 json 文件内的资源内使用 for_each 时出现 Terraform JSON 错误

arrays - 如何使用 jq 将 JSON 文件分解为包裹在数组中的较小 json?

json - 使用 JQ 替换 JSON 模板中的变量