简体   繁体   English

使用JQ按键组合两个Json

[英]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.我有两个 json,它们是共享相同密钥的对象列表,我正在尝试使用 jq 将它们组合成一个 json。 The expected output is a single json that contains a list of the combined objects in list form.预期的 output 是单个 json,其中包含列表形式的组合对象列表。 For example:例如:

Json 1: Json 1:

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

Json 2: 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合并Json

[
{"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:我已经尝试了几种方法来合并我在这个线程中找到的这些 json,例如:

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

I am still a novice in jq, so any help would be appreciated!我仍然是 jq 的新手,所以任何帮助将不胜感激!

Use the SQL-Style Operators JOIN and INDEX使用SQL 风格的运算符JOININDEX

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演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM