Reputation: 4510
I have a bit of a weird data setup, I have the following json files:
file 1:
[
["04-05-2020",
12
],
["03-05-2020",
16
]
]
file 2:
[
["04-05-2020",
50
],
["03-05-2020",
70
]
]
I want to merge the 2 json files using the Dates (which are not specified as keys) and reassign keys and values to the output, such that the output is something like: file 1:
[
{date: "04-05-2020",
value1 : 12,
value2 : 50
},
{date: "03-05-2020",
value1 : 16,
value2: 70
}
]
My thoughts are I might have to merge the files together first and do some kind of reduce operation on the dates in the array, but my attempts have so far been unsuccessful. Or perhaps I should be formatting the Array first into Key + Value and then do a jq -s 'add'? I'm actually not sure how to reformat this.
Upvotes: 1
Views: 226
Reputation: 116680
If the arrays in file1.json and file2.json are in lockstep as in your example, you could simply write:
.[0] |= map({date: .[0], value1: .[1]})
| .[1] |= map({date: .[0], value2: .[1]})
| transpose
| map(add)
using an invocation along the lines:
jq -s -f program.jq file1.json file2.json
Of course there are many variations.
Upvotes: 2
Reputation: 50750
One way of doing it using reduce
:
reduce inputs[] as [$date, $value] ({};
if has($date) then
.[$date] += {value2: $value}
else
.[$date] = {$date, value1: $value}
end
) | map(.)
Note that you need to specify -n
/--null-input
option on the command line in order for inputs
to work.
Upvotes: 2