如何通过匹配键值对来合并JSON文件数组中的对象?

huangapple go评论61阅读模式
英文:

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 &#39;reduce inputs[] as $obj ({};
  .[$obj.lang] += $obj
) | map(.)&#39; file1.json file2.json

<sup>Online demo</sup>

huangapple
  • 本文由 发表于 2023年5月21日 20:02:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76299813.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定