簡體   English   中英

根據鍵值解析2個文件並重新創建另一個json文件[JQ]

[英]Parse 2 files based on key value and recreate another json file [JQ]

我是 JQ 的新手。 我需要根據另外 2 個文件制作一個 json 文件。 我整天都在使用它並在這里堆棧。 非常需要這個。

這是文件 1

{
"name": "foo",
  "key": "1",
  "id": "x"
}
{
  "name": "bar",
  "key": "2",
  "id": "x"
}
{
  "name": "baz",
  "key": "3",
  "id": "y"
}

檔案 2

{
"name": "a",
  "key": "1"
}
{
  "name": "b",
  "key": "1"
}
{
  "name": "c",
  "key": "2"
}
{
  "name": "d",
  "key": "2"
}
{
  "name": "e",
  "key": "3"
}

預期結果:

{
"x": {
    "foo": [
      "a",
      "b"
    ],
    "bar": [
      "c",
      "d"
    ]
  },
  "y": {
    "baz": [
      "e"
    ]
  }
}

我可以用 python 腳本來做,但我需要用 jq。

提前致謝。

使用reduce的第一個文件的項目( $i )依次建立使用結果對象setpath從項目的字段和值在輔助字典文件(一個匹配的地圖$d )。

jq -s --slurpfile d file2 '
  reduce .[] as $i ({}; setpath(
    [$i.id, $i.name];
    [$d[] | select(.key == $i.key).name]
  ))
' file1

為了效率,下面的方案首先基於file2構造一個“字典”; 此外,它這樣做而不必“啜飲”它。

< file2 jq -nc --slurpfile file1 file1 '
  (reduce inputs as {$name, $key} ({};
      .[$key] += [$name])) as $dict
  | reduce $file1[] as {$name, $key, $id} ({};
      .[$id] += [ {($name): $dict[$key]} ] )
'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM