gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:43:28 25 4
gpt4 key购买 nike

我有两个包含一些 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com