Linux
如何使用JQ在兩個JSON中合併多個數組中的數組
我有兩個 JSON 文件 (
file1.json
和file2.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
有沒有辦法修改這個函式來結合
list1
和list2
?
假設所有文件的最頂層鍵在所有文件中始終相同,將鍵提取到單獨的變數中,然後通過這些鍵減少(累積)數據。
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]}] }
您將獲得以下包含兩個對象的結果文件:
{ "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