26

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"}

请建议我

4

2 回答 2

62

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

$ 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"
}
于 2013-05-30T11:57:51.047 回答
17
sed -i '$s/}/,\n"location":"canada"}/' sample.json

结果:

{"name" :"sam",
"age":23,
"designation":"doctor",
"location":"canada"}
于 2013-05-30T05:01:24.333 回答