Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merge json files on a "primary key" using jq

I have two files containing json arrays like so

file1.json

[
  {
    "classid":"abc",
    "name":"Alex"
  },
  {
    "classid":"abc",
    "name":"Bob"
  }
]

file2.json

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  {
    "classid":"abc",
    "classname":"math"
  }
]

I’d like to combine these two files on "classid".
Desired output.json

[
  {
    "classid":"abc",
    "name":"Alex",
    "classname":"math
  },
  {
    "classid":"abc",
    "name":"Bob",
    "classname":"math
  }
]

I tried
> jq -s 'reduce .[] as $item ({}; . *= $item)' file1.json file2.json
but I see a jq: error (at file1.json:10): object ({}) and array ([{"classid...) cannot be multiplied

Would appreciate any help.

>Solution :

If you have jq 1.6, just use JOIN with an INDEX:

jq '[JOIN(INDEX(input[]; .classid); .[]; .classid; add)]' file1.json file2.json
[
  {
    "classid": "abc",
    "name": "Alex",
    "classname": "math"
  },
  {
    "classid": "abc",
    "name": "Bob",
    "classname": "math"
  }
]

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading