json - 使用 jq 更新 JSON 文件时缺少内容

标签 json linux bash ubuntu jq

如果我们有 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/

相关文章:

c - sigtimedwait() 在超时前返回 EAGAIN

C++、 sleep 和循环

ruby-on-rails - 问题 : Could not load OpenSSL

linux - 第一个 bash 脚本不工作

html - 使用 sed 从文件中删除空的 HTML 标签

javascript - jQuery 在选择更改时显示/隐藏 div 不适用于 JSON 填充选项

c# - 如何检查 Json 是否匹配特定的 C# 类型?

javascript - 希望在 Sequelize/Postgres DB 查询中迭代 JSON 以找到匹配的值

json - 可以在 Go 中获取 JSON 的值

bash - GNU 并行输出进度同时输出到文件