简体   繁体   English

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

[英]how to add json object to json file using shell script

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 请建议我

To merge two json objects, you could use jq command-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"
}
sed -i '$s/}/,\n"location":"canada"}/' sample.json

Result: 结果:

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

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

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