Home > OS >  Combine two Json's by key using JQ
Combine two Json's by key using JQ

Time:03-22

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:

[
{"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!

CodePudding user response:

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

  • Related