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

but it results

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

但我希望它是这样的

{"name" :"sam",
"age":23,
"designation":"doctor", 
"location":"canada"}
    
1 个评论
Shell脚本不是很适合这项任务。你应该尝试找到一个真正能理解JSON的工具。如果你知道Python,可以看一下json.tool.
linux
json
shell
user2353439
user2353439
发布于 2013-05-30
2 个回答
jfs
jfs
发布于 2013-05-30
已采纳
0 人赞同

To merge two json objects, you could use 替换代码0】 命令行工具:

$ jq -s add sample.json another.json

Output:

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

要更新一个单一的属性。

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

它产生相同的输出。

"doctor"加到位置上。

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

Output:

"name": "sam", "age": 23, "designation": "doctor", "location": "doctorcanada"
我只用jq工作了5分钟,但它非常灵活。我强烈推荐这个,而不是用ed/sed/awk做复杂的东西。
jq '.location="canada"' sample.json是唯一起作用的,但它没有追加到sample.json;它只是把它打印到屏幕上。 整个想法是我们想追加到一个子文件。 jq -s add一直给出 "解析错误。在第3行第32列有无效的数字字样"。 即使你删除 "年龄":23,你仍然得到 "无效的数字字面"。 这对你们来说是怎样的呢?
jfs
@Bear: all examples in the answer work (I've just checked again on the current jq version on my machine: jq --version -> jq-1.5-1-a5b5cbe). All examples print to the screen (you don't want to corrupt your input data while you're adapting the filter for your case. If you don't know how to save the output to a file; ask). I see that someone has upvoted your comment. Does it mean there is an environment where jq doesn't work?
For your convenience jq ... INPUT > INPUT.tmp && mv INPUT.tmp INPUT stackoverflow.com/questions/36565295/...
perreal
perreal
发布于 2013-05-30
0 人赞同
sed -i '$s/}/,\n"location":"canada"}/' sample.json

Result: