如何在两个文件中比较数组的每个对象中共有的一个字段,以及如何更新数组 [英] how to compare one field that is common in each object of an array in two files and do update the array as well
问题描述
示例 input1.json
[{
"organizationId": "org1",
"test1": "UP",
"key1": "value1"
},
{
"organizationId": "org2",
"test1": "UP",
"key1": "value3"
}]
示例 input2.json
[{
"organizationId": "org1",
"test2": "DOWN",
"key1": "value4"
},
{
"organizationId": "org3",
"test2": "DOWN",
"key1": "value5"
}]
预期 output.json
[{
"organizationId": "org1",
"test1": "UP",
"key1": "value4",
"test2": "DOWN"
},
{
"organizationId": "org2",
"test1": "UP",
"key1": "value3"
},
{
"organizationId": "org3",
"test2": "DOWN",
"key1": "value5"
}
]
输入是两个文件的数组对象.我的目标是合并两个具有相同值的对象,并保持其他对象不变.我通过分组
The input is an array object of two files. My objective is to merge two objects if they have same value and leave other objects intact. I partially achieved this by grouping
jq -s '[ .[0] + .[1] | group_by(.organizationId)[] | select(length > 1) |add ]' ìnput1.json input2.json
通过 organizationId 对对象进行分组.在两个输入中,"organizationId":"org1" 可用,因此可以将其分组.现在我面临的问题是我正在从 input1.json 和"organizationId":"org3"中丢失其他对象"organizationId":"org2" 来自 input2.json ,但彼此之间都不存在.
Group objects by organizationId. In both the inputs, "organizationId": "org1" is available so it can be grouped. Now the problem I'm facing is I'm loosing other objects "organizationId": "org2" from input1.json and "organizationId": "org3" from input2.json which doesn't exist in each others file.
已经实现了分组的基本原理,但是即使没有匹配项,我也需要保留两个文件中的任何其他对象.如果要保留其他对象,是否应该使用 group_by ?如果没有,如何使用 jq 获得预期的输出?
The basic principle of grouping is achieved but I do need to preserve any other objects from both the files even if there is no match. Should we use group_by if we want to preserve other objects? If not, how can I achieve the expected output using jq?
推荐答案
对于更广泛的受众,获取所有对象(分组和未分组)的解决方案,请在下面使用
For wider audience, solution to get all objects (grouped & ungrouped), use below
jq -s '[ .[0] + .[1] | group_by(.organizationId)[] |add ]' ìnput1.json input2.json
如果仅将对象分组,则在下面使用.
If only grouped objects, then use below.
jq -s '[ .[0] + .[1] | group_by(.organizationId)[] | select(length > 1) | add ]' ìnput1.json input2.json
我不得不说 jq如此强大! :)
这篇关于如何在两个文件中比较数组的每个对象中共有的一个字段,以及如何更新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!