Linux 如何使用shell脚本将json对象添加到json文件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16828187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:04:50  来源:igfitidea点击:

how to add json object to json file using shell script

linuxjsonshell

提问by user2353439

json file as follows:

json文件如下:

{"name" :"sam",
"age":23,
"designation":"doctor"}

now i want to add another json object {"location":"canada"} at the end of the file using bash script i have tried echo "{"location":"canada"}">>sample.json

现在我想使用 bash 脚本在文件末尾添加另一个 json 对象 {"location":"canada"} 我试过 echo "{"location":"canada"}">>sample.json

but it results

但结果

{"name" :"sam",
"age":23,
"designation":"doctor"} {location:canada}

but i want it to be like this

但我希望它是这样的

{"name" :"sam",
"age":23,
"designation":"doctor", 
"location":"canada"}

please suggest me

请给我建议

采纳答案by perreal

sed -i '$s/}/,\n"location":"canada"}/' sample.json

Result:

结果:

{"name" :"sam",
"age":23,
"designation":"doctor",
"location":"canada"}

回答by jfs

To merge two json objects, you could use jqcommand-line utility:

要合并两个 json 对象,您可以使用jq命令行实用程序

$ jq -s add sample.json another.json

Output:

输出:

{
  "name": "sam",
  "age": 23,
  "designation": "doctor",
  "location": "canada"
}

To update a single attribute:

要更新单个属性:

$ jq '.location="canada"' sample.json

It produces the same output.

它产生相同的输出。

To prepend "doctor"to the location:

要添加"doctor"到位置:

$ jq '.location = "doctor" + .location' input.json

Output:

输出:

{
  "name": "sam",
  "age": 23,
  "designation": "doctor",
  "location": "doctorcanada"
}