json文件如下:
{"name" :"sam",
"age":23,
"designation":"doctor"}
现在我想使用bash脚本在文件末尾添加另一个json对象{“location”:“canada”} 我试过echo“{”location“:”canada“}”>> sample.json
但结果
{"name" :"sam",
"age":23,
"designation":"doctor"} {location:canada}
但我希望它像这样
{"name" :"sam",
"age":23,
"designation":"doctor",
"location":"canada"}
请建议我
答案 0 :(得分:42)
要合并两个json对象,可以使用jq
command-line utility:
$ jq -s add sample.json another.json
输出:
{
"name": "sam",
"age": 23,
"designation": "doctor",
"location": "canada"
}
更新单个属性:
$ jq '.location="canada"' sample.json
它产生相同的输出。
将"doctor"
添加到该位置:
$ jq '.location = "doctor" + .location' input.json
输出:
{
"name": "sam",
"age": 23,
"designation": "doctor",
"location": "doctorcanada"
}
答案 1 :(得分:10)
sed -i '$s/}/,\n"location":"canada"}/' sample.json
结果:
{"name" :"sam",
"age":23,
"designation":"doctor",
"location":"canada"}