如何使用 JQ 将两个 JSON 中的多个数组合并

如何使用 JQ 将两个 JSON 中的多个数组合并

我有两个 JSON 文件(file1.jsonfile2.json),其结构与下面定义的相同,并带有两个数组列表,如下所示。

第一个文件是(file1.json):

{
  "Lists1": [
   {
      "point": "a",
      "coordinates": [
        2289.48096,
        2093.48096
      ]
   }
  ],
  "Lists2": [
   {
      "point": "b",
      "coordinates": [
        2289.48096,
        2093.48096
      ]
   }
 ]
}

第二个文件是(file2.json):

{
  "Lists1": [
   {
      "point": "c",
      "coordinates": [
        2289.48096,
        2093.48096
      ]
   }
  ],
  "Lists2": [
   {
      "point": "d",
      "coordinates": [
        2289.48096,
        2093.48096
      ]
   }
 ]
}

所以我的预期输出将是:

{
  "Lists1": [
   {
      "point": "a",
      "coordinates": [
        2289.48096,
        2093.48096
      ]
   },
   {
      "point": "c",
      "coordinates": [
        2289.48096,
        2093.48096
      ]
   }
  ]
  "Lists2": [
   {
      "point": "b",
      "coordinates": [
        2289.48096,
        2093.48096
      ]
   },
   {
      "point": "d",
      "coordinates": [
        2289.48096,
        2093.48096
      ]
   }
 ]
}

我正在尝试使用 合并(合并)这两个文件jq。我发现使用下面的命令,但这仅适用于一个列表。

jq -n '{ list1: [ inputs.list1 ] | add }' file1.json file2.json

有没有办法修改这个函数以结合list1list2

答案1

假设所有文档的最顶层键在所有文档中始终相同,请将键提取到单独的变量中,然后减少(累积)这些键上的数据。

jq -s '
    (.[0] | keys[]) as $k |
    reduce .[] as $item (null; .[$k] += $item[$k])' file*.json

请注意使用-s将所有输入读取到单个数组中。

这或多或少会迭代键Lists1Lists2每个文档,将数据累积到新的结构中(null从头开始)。

假设输入 JSON 文档格式良好:

{
"Lists1": [{"point":"a","coordinates":[2289.48096,2093.48096]}],
"Lists2": [{"point":"b","coordinates":[2289.48096,2093.48096]}]
}
{
"Lists1": [{"point":"c","coordinates":[2289.48096,2093.48096]}],
"Lists2": [{"point":"d","coordinates":[2289.48096,2093.48096]}]
}

您将得到以下包含两个对象的结果文档:

{
"Lists1": [{"point":"a","coordinates":[2289.48096,2093.48096]},{"point":"c","coordinates":[2289.48096,2093.48096]}]
}
{
"Lists2": [{"point":"b","coordinates":[2289.48096,2093.48096]},{"point":"d","coordinates":[2289.48096,2093.48096]}]
}

您希望两个键位于同一个对象中吗:

jq -s '
    [ (.[0] | keys[]) as $k |
      reduce .[] as $item (null; .[$k] += $item[$k]) ] | add' file*.json

答案2

如果钥匙是不是在整个文档中始终相同,这将完成这项工作:

jq --slurp '
    reduce (.[] | to_entries | .[]) as {$key, $value} (
        {};
        .[$k] += $v
    )
    ' file*.json

鉴于这两个文件:

{
    "Lists1": [{"point":"a","coordinates":"..."],
    "Lists2": [{"point":"b","coordinates":"..."}]
}
{
    "Lists1": [{"point":"c","coordinates":"..."}],
    "Lists2": [{"point":"d","coordinates":"..."}],
    "Lists3": [{"point":"e","coordinates":"..."}]
}

输出是:

{
    "Lists1":[{"point":"a","coordinates":"..."},{"point":"c","coordinates":"..."}],
    "Lists2":[{"point":"b","coordinates":"..."},{"point":"d","coordinates":"..."}],
    "Lists3":[{"point":"e","coordinates":"..."}]
}

相关内容