JQ按键分组,合并值,然后展平对象

时间:2019-03-03 22:34:37

标签: jq

使用以下输入:

# file1.json
{
  "uid": "1",
  "name": "jack"
}
{
  "uid": "2",
  "name": "jill"
}

# file2.json
{
  "fid": "a",
  "file": "sample1.txt",
  "uid": "1"
}
{
  "fid": "b",
  "file": "sample2.txt",
  "uid": "1"
}
{
  "fid": "c",
  "file": "sample3.txt",
  "uid": "2"
}

如何将name键值对插入file2.json中的对象。我试图获得的输出如下:

{
  "fid": "a",
  "file": "sample1.txt",
  "uid": "1",
  "name": "jack"
}
{
  "fid": "b",
  "file": "sample2.txt",
  "uid": "1",
  "name": "jack"
}
{
  "fid": "c",
  "file": "sample3.txt",
  "uid": "2",
  "name": "jill"
}

merge json objects with jqjoin two json files based on common key with jq utility or alternative way from command line上发布的解决方案似乎都只返回最后一个匹配对。见下文。

{"uid":"1","name":"jack","fid":"b","file":"sample2.txt"}
{"uid":"2","name":"jill","fid":"c","file":"sample3.txt"}

1 个答案:

答案 0 :(得分:3)

您将需要“抓取” file1.json,例如通过调用jq如下:

jq -n -f merge.jq --slurpfile file1 file1.json file2.json

merge.jq包含:

INDEX($file1[]; .uid) as $dict
| inputs
| . + $dict[.uid]

def INDEX

如果您的jq没有INDEX / 2,则只需添加其def:

def INDEX(stream; idx_expr):
  reduce stream as $row ({}; .[$row|idx_expr|tostring] = $row);