nelasx
nelasx

Reputation: 191

Append to array in json file from another json file with "jq"

i have a file "stats.json" with the following initial structure"

[{
"price": 66.55,
"created": "2018-02-24T14:32:57"
}]

With a bash/curl script i take every 10 minutes data from an api and save it to "temp.json"

{
"price": 88.55,
"created": "2018-02-24T15:32:57"
}

I would like to merge the temp.json (which is updated every 10min) and to fill the stats.json file. I tried to do it with "jq" but without success.

Upvotes: 1

Views: 7797

Answers (1)

peak
peak

Reputation: 116720

One way to add the item in temp.obj to the array in stats.json:

jq —-slurpfile temp temp.obj '. + $temp' stats.json

Another way:

jq —s '.[0] + [.[1]]' stats.json temp.json

(If you want to overwrite stats.json, then I’d suggest using sponge as illustrated below.)

However, if at all possible, it would almost certainly be better to maintain stats.json as a log file in JSONL format: http://jsonlines.org/

That is, each object in temp.json would be appended as a single line to stats.json:

jq -c temp.json >> stats.json

This of course assumes that stats.json is initially empty or already in the JSONL format. To convert your existing stats.json to JSONL, you could do something like this:

cp -p stats.json stats.json.bak

jq -c .[] stats.json | sponge stats.json

Upvotes: 4

Related Questions