使用以下输入:
# 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 jq和join 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"}
答案 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]
如果您的jq没有INDEX / 2,则只需添加其def:
def INDEX(stream; idx_expr):
reduce stream as $row ({}; .[$row|idx_expr|tostring] = $row);