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

Combine two Json's by key using JQ

I have two json’s that are a list of objects that share the same key and I am trying to combine them into one json using jq. The expected output is a single json that contains a list of the combined objects in list form. For example:

Json 1:

[
{"Id":"1", "FirstName":"firstName1", "LastName":"lastName1"},
{"Id":"2", "FirstName":"firstName2", "LastName":"lastName2"},
{"Id":"3", "FirstName":"firstName2", "LastName":"lastName3"}
]

Json 2:

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

[
{"School":"School1", "Id":"1", "Degree":"Degree1"},
{"School":"School2", "Id":"2", "Degree":"Degree2"},
{"School":"School3", "Id":"3", "Degree":"Degree3"}
]

Combined Json Based on Id

[
{"Id":"1", "FirstName":"firstName1", "LastName":"lastName1",
"School":"School1", "Degree":"Degree1"},
{"Id":"2", "FirstName":"firstName2", "LastName":"lastName2",
"School":"School2", "Degree":"Degree2"},
{"Id":"3", "FirstName":"firstName2", "LastName":"lastName3",
"School":"School3", "Degree":"Degree3"}
]

I have already tried a few ways to merge these jsons I found in this thread such as:

jq -s '.[0] * .[1]' file1 file2

I am still a novice in jq, so any help would be appreciated!

>Solution :

Use the SQL-Style Operators JOIN and INDEX

jq 'JOIN(INDEX(inputs[];.Id);.[];.Id;add)' json1 json2
[
  {
    "Id": "1",
    "FirstName": "firstName1",
    "LastName": "lastName1",
    "School": "School1",
    "Degree": "Degree1"
  },
  {
    "Id": "2",
    "FirstName": "firstName2",
    "LastName": "lastName2",
    "School": "School2",
    "Degree": "Degree2"
  },
  {
    "Id": "3",
    "FirstName": "firstName2",
    "LastName": "lastName3",
    "School": "School3",
    "Degree": "Degree3"
  }
]

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