我有两个文件。
第一:
[
{ "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" }
]
}
]
我尝试了其他选项,但无法达到预期的结果。
答案 0 :(得分:2)
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
答案 1 :(得分:1)
以下解决方案着重于效率,还提出了输出的另一种格式:
add as $dict
# aggregation:
| (reduce input[] as $record ({};
($record|keys_unsorted[0]) as $person
| if $dict[$person] then .[$person] += [$record[$person]] else . end )) as $answer
# re-arrangement
| reduce ($dict|keys_unsorted[]) as $person ([]; . + [ {($person): $answer[$person] } ] )
jq -f merge.jq first.json second.json