英文:
How to join objects within array of json files by matching key:value?
问题
给定 file1.json 和 file2.json,其中的对象具有相同的 "lang" 属性并且其值相同:
[
{ "lang": "Inari Sami", "audios": 78 },
{ "lang": "Tofalar", "audios": 42 },
{ "lang": "Kumyk", "audios": 305 }
]
[
{ "lang": "Inari Sami", "isoCode": "smn", "genderFemales": 1, "genderMales": 5, "genderOthers": 3 },
{ "lang": "Tofalar", "genderFemales": 2, "genderMales": 3, "genderOthers": 1 },
{ "lang": "Kumyk", "isoCode": "kum", "genderFemales": 5, "genderMales": 4, "genderOthers": 2 },
{ "lang": "French"}
]
如何获得这些对象的合并,如下所示:
[
{ "lang": "Inari Sami", "audios": 78, "isoCode": "smn", "genderFemales": 1, "genderMales": 7, "genderOthers": 1 },
{ "lang": "Tofalar", "audios": 42, "isoCode": "xal", "genderFemales": 2, "genderMales": 6, "genderOthers": 0 },
{ "lang": "Kumyk", "audios": 305, "isoCode": "kum", "genderFemales": 5, "genderMales": 7, "genderOthers": 1 },
{ "lang": "French"}
]
英文:
Given file1.json and file2.json with objects sharing a common "lang" properties with identical values :
[
{ "lang": "Inari Sami", "audios": 78 },
{ "lang": "Tofalar", "audios": 42 },
{ "lang": "Kumyk", "audios": 305 }
]
[
{ "lang": "Inari Sami", "isoCode": "smn", "genderFemales": 1, "genderMales": 5, "genderOthers": 3 },
{ "lang": "Tofalar", "genderFemales": 2, "genderMales": 3, "genderOthers": 1 },
{ "lang": "Kumyk", "isoCode": "kum", "genderFemales": 5, "genderMales": 4, "genderOthers": 2 },
{ "lang": "French"}
]
How can I get a consolidation (fusion) of those such as :
[
{ "lang": "Inari Sami", "audios": 78, "isoCode": "smn", "genderFemales": 1, "genderMales": 7, "genderOthers": 1 },
{ "lang": "Tofalar", "audios": 42, "isoCode": "xal", "genderFemales": 2, "genderMales": 6, "genderOthers": 0 },
{ "lang": "Kumyk", "audios": 305, "isoCode": "kum", "genderFemales": 5, "genderMales": 7, "genderOthers": 1 },
{ "lang": "French"}
]
答案1
得分: 2
这是一种方式:
jq -s 'add | group_by(.lang) | map(add)' file1.json file2.json
另一种方式:
jq -n 'reduce inputs[] as $obj ({}; .[$obj.lang] += $obj ) | map(.)' file1.json file2.json
英文:
Here is one way:
jq -s 'add | group_by(.lang) | map(add)' file1.json file2.json
<sup>Online demo</sup>
and another:
jq -n 'reduce inputs[] as $obj ({};
.[$obj.lang] += $obj
) | map(.)' file1.json file2.json
<sup>Online demo</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论