我有两个文件。
第一:
[
{ "person1": [] },
{ "person2": [] }
]
第二:
[
{
"person2": { "attribute1": "wer", "attribute2": "sdf" }
},
{
"person2": { "attribute1": "ert", "attribute2": "dfg" }
},
{
"person2": { "attribute1": "rty", "attribute2": "fgh" }
},
{
"person3": { "attribute1": "tyu", "attribute2": "ghj" }
},
{
"person1": { "attribute1": "yui", "attribute2": "hjk" }
}
]
我尝试使用jq
合并它们。对于第一个文件中的每个人(第二个文件中可能有更多人,应该忽略)创建其属性列表。所以输出应该是这样的:
[
{
"person1":
[
{ "attribute1": "yui", "attribute2": "hjk" }
]
},
{
"person2":
[
{ "attribute1": "wer", "attribute2": "sdf" },
{ "attribute1": "ert", "attribute2": "dfg" },
{ "attribute1": "rty", "attribute2": "fgh" }
]
}
]
我尝试了不同的选择,但无法达到预期的结果。
最佳答案
jq 'reduce (input[]|to_entries[]) as $e (add;
if has($e.key) then .[$e.key] += [$e.value] else . end
) | [keys_unsorted[] as $k|{($k): .[$k]}]' file1 file2
<子> online demo
关于json - 使用 jq 合并两个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57637890/