JQを使用して2つのJSONの複数の配列をマージする方法

JQを使用して2つのJSONの複数の配列をマージする方法

以下に定義されているのと同じ構造を持つ2つのJSONファイル(file1.jsonおよび)があり、以下に示す2つの配列のリストがあります。file2.json

最初のファイルは(file1.json)です。

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

2番目のファイルは(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
      ]
   }
 ]
}

これら2つのファイルをマージ(マージ)する方法を使用しようとしていますjq。以下のコマンドを使用して見つけましたが、これはリストでのみ機能します。

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

list1sumを結合するためにこの関数を変更する方法はありますかlist2

ベストアンサー1

最上位キーがすべての文書で常に同じであると仮定し、キーを別々の変数として抽出し、そのキーのデータを減らします(累積)。

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

を使用すると、-sすべての入力を単一の配列として読み込みます。

Lists1これにより、キーと各文書がある程度繰り返され、Lists2データが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]}]
}

2 つのオブジェクトを含む次の結果文書を取得します。

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

おすすめ記事