JQ按键加入JSON文件 [英] JQ Join JSON files by key
问题描述
Looks like it's not actual for jq 1.4, could you provide any other ways to join JSON files by key? e.g
{
"key": "874102296-1",
"que_lat": "40"
}
{
"key": "874102296-2",
"que_lat": "406790"
}
和
{
"key": "874102296-1",
"in_time": "1530874104733",
"latency": "12864258288242"
}
{
"key": "874102296-2",
"in_time": "1530874104746"
}
因此,我想要这样的东西:
As a result, i'd like to have something like this:
{
"key": "874102296-1",
"in_time": "1530874104733",
"full_latency": "12864258288242",
"que_lat": "40"
}
{
"key": "874102296-2",
"in_time": "1530874104746",
"que_lat": "406790"
}
谢谢!
推荐答案
使用您引用的SO页面中给出的hashJoin def,可以轻松解决该问题.
The problem can easily be solved using the def of hashJoin given in the SO page that you cite.
如果您的jq 1.5或更高版本,则可以使用以下调用:
If you have jq 1.5 or higher, you could use this invocation:
jq -n --slurpfile f1 file1.json --slurpfile f2 file2.json -f join.jq
其中join.jq包含hashJoin的第二个定义,以及:
where join.jq contains the second def of hashJoin, together with:
hashJoin($f1; $f2; .key)[]
使用jq 1.4的解决方案
如果您有jq 1.4,则棘手的问题是将两个文件中的每个文件分别读取为一个数组.这是一种假设bash的方法:
Solution using jq 1.4
If you have jq 1.4, the trickiness is to read each of the two files separately as an array. Here's one approach that assumes bash:
jq -n --argfile f1 <(jq -s . file1.json) --argfile f2 <(jq -s . file2.json) -f join.jq
其中join.jq与上面相同.
where join.jq is as above.
如果您不能使用bash,则创建临时文件可能是最简单的.
If you cannot use bash, then it might be simplest to create temporary files.
这篇关于JQ按键加入JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!