如果我们有 hello.json
$ echo '{"hello": "world"}' > hello.json
$ cat hello.json
{"hello": "world"}
并尝试添加"foo": "bar"
使用 jq
,文件hello.json
变成一个空文件。$ cat hello.json | jq --arg bar bar '. + {foo: $bar}' > hello.json
$ cat hello.json
另一方面,如果我们改为将新的 JSON 有效负载写入 world.json
,我们得到world.json
中的预期内容.$ echo '{"hello": "world"}' > hello.json
$ cat hello.json
{"hello": "world"}
$ cat hello.json | jq --arg bar bar '. + {foo: $bar}' > world.json
$ cat world.json
{
"hello": "world",
"foo": "bar"
}
有没有办法做到这一点无需安装新实用程序 喜欢 sponge
?
最佳答案
这不是 jq 问题,而是输出重定向在 shell 中的工作方式。当您使用 >
重定向到文件时,文件在命令执行前被截断。
您必须写入另一个文件,然后将其复制到旧文件上。 (或使用 sponge
)。
作为(广义)代码:
$ cmd < file > file.tmp
$ mv file.tmp file
或者$ cmd file > file.tmp
$ mv file.tmp file
关于json - 使用 jq 更新 JSON 文件时缺少内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72416842/