简体   繁体   English

使用“jq”从另一个 json 文件附加到 json 文件中的数组

[英]Append to array in json file from another json file with “jq”

i have a file "stats.json" with the following initial structure"我有一个具有以下初始结构的文件“stats.json”

[{
"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"使用 bash/curl 脚本,我每 10 分钟从 api 中获取一次数据并将其保存到“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.我想合并 temp.json(每 10 分钟更新一次)并填充 stats.json 文件。 I tried to do it with "jq" but without success.我试图用“jq”来做,但没有成功。

One way to add the item in temp.obj to the array in stats.json:将 temp.obj 中的项添加到 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.) (如果你想覆盖 stats.json,那么我建议使用如下图所示的sponge 。)

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/但是,如果可能的话,将 stats.json 维护为 JSONL 格式的日志文件几乎肯定会更好: http ://jsonlines.org/

That is, each object in temp.json would be appended as a single line to stats.json:也就是说,temp.json 中的每个对象都将作为一行附加到 stats.json:

jq -c temp.json >> stats.json

This of course assumes that stats.json is initially empty or already in the JSONL format.这当然假设 stats.json 最初是空的或已经是 JSONL 格式。 To convert your existing stats.json to JSONL, you could do something like this:要将现有的 stats.json 转换为 JSONL,您可以执行以下操作:

cp -p stats.json stats.json.bak

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM