jq-合并两个“不能相乘"的JSON文件时发生错误. [英] jq - error when merging two JSON files "cannot be multiplied"
问题描述
我有两个包含JSON的文件.
I have two files containing some JSON.
File1-有些值可以是字符串,有些可能为null,始终设置VolumeId.
File1 - some values can be a string, some might be null, VolumeId is always set.
[
{
"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可以为null,也可以不为null.
File2 - VolumeId will always match as those in File1, and Tag7 may or may not be null.
[
{
"VolumeId": "vol-xxxxxxx1",
"Tag7": "Tag7Value"
},
{
"VolumeId": "vol-xxxxxxx2",
"Tag7": "Tag7Value"
},
{
"VolumeId": "vol-xxxxxxx3",
"Tag7": "null"
}
]
我需要将它们组合成一个JSON数组:
I need to combine these into one JSON array:
[
{
"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"
}
]
尝试使用以下命令时出现错误:
I get an error when trying to use the below command:
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
赋值.最终结果如下所示:
I'm assuming you want to merge all entries that have the same .VolumeId
into one. To do so, first we flatten
the array of arrays of objects into an array of objects. Then, we group_by(.VolumeId)
. Finally, we map
over each group and reduce
it by calculating the product of all its elements. The final results looks like this:
jq -s 'flatten | group_by(.VolumeId) | map(reduce .[] as $x ({}; . * $x))' /path/to/file1 /path/to/file2
这篇关于jq-合并两个“不能相乘"的JSON文件时发生错误.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!