简体   繁体   English

根据键值解析2个文件并重新创建另一个json文件[JQ]

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

I am new to JQ.我是 JQ 的新手。 I need to make a json file based on another 2 files.我需要根据另外 2 个文件制作一个 json 文件。 I am worked with it whole day and stack here.我整天都在使用它并在这里堆栈。 Badly need this.非常需要这个。

Here is file 1这是文件 1

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

file 2档案 2

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

Expected Result:预期结果:

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

I can do it with python script but I need it with jq.我可以用 python 脚本来做,但我需要用 jq。

Thanks in advance.提前致谢。

Use reduce on the first file's items ( $i ) to successively build up the result object using setpath with fields from the item and values as a matching map on the secondary dictionary file ( $d ).使用reduce的第一个文件的项目( $i )依次建立使用结果对象setpath从项目的字段和值在辅助字典文件(一个匹配的地图$d )。

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

For efficiency, the following solution first constructs a "dictionary" based on file2;为了效率,下面的方案首先基于file2构造一个“字典”; furthermore, it does so without having to "slurp" it.此外,它这样做而不必“啜饮”它。

< 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