Olya Orlova
Olya Orlova

Reputation: 25

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"
}

and

{
  "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"
}

Thanks!

Upvotes: 1

Views: 1831

Answers (1)

peak
peak

Reputation: 116870

The problem can easily be solved using the def of hashJoin given in the SO page that you cite.

Solution using jq 1.5 or higher

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

where join.jq contains the second def of hashJoin, together with:

hashJoin($f1; $f2; .key)[]

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 

where join.jq is as above.

If you cannot use bash, then it might be simplest to create temporary files.

Upvotes: 2

Related Questions