【问题标题】:how to add json object to json file using shell script如何使用 shell 脚本将 json 对象添加到 json 文件
【发布时间】:2013-05-25 13:22:42
【问题描述】:

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

请给我建议

【问题讨论】:

  • Shell 脚本不太适合此任务。您应该尝试找到一个真正理解 JSON 的工具。如果您了解 Python,请查看 json.tool

标签: linux json shell


【解决方案1】:
sed -i '$s/}/,\n"location":"canada"}/' sample.json

结果:

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

【讨论】:

  • 感谢它运行良好我还有一个要求,我想将一个 json 对象值附加到另一个对象。例如,我想将“医生”附加到加拿大,结果应该是 {“name”:“sam”,“age”:23,“designation”:“doctor”,“location”:“doctorcanada”}
  • @kampu: 使用sed 使用正则表达式操作json 数据是脆弱且不必要的复杂。 There are better alternatives.
  • 仅供参考——如果您在 Mac 上执行 sed -i...,则会收到此错误:“sed: 1: "sample.json": unterminated substitution pattern"。但如果你在 Linux (Ubuntu) 中这样做,那就没问题了。
  • 有人知道如何在该语句中使用变量吗?如果您这样做:loc="canada",然后执行sed -i '$s/}/,\n"location":"$loc"}/' sample.json,则不起作用。它不是渲染变量,而是放置 "location":"$loc"。
  • '$s/}/,\n"location":"'$loc'"}/'
【解决方案2】:

要合并两个 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"
}

【讨论】:

  • 我只使用了 jq 5 分钟,但它非常灵活。我强烈推荐这个,而不是用 ed/sed/awk 做复杂的事情。
  • jq '.location="canada"' sample.json 是唯一有效的方法,但它没有附加到 sample.json;它只是将其打印到屏幕上。整个想法是我们想附加到一个子文件。 jq -s add 不断给出“解析错误:第 3 行第 32 列的数字文字无效”。即使您删除“年龄”:23,您仍然会得到“无效的数字文字”。这对你们有什么作用?
  • @Bear:答案中的所有示例都有效(我刚刚再次检查了我机器上当前的jq 版本:jq --version -> jq-1.5-1-a5b5cbe)。所有示例都打印到屏幕上(您不希望在为您的案例调整过滤器时损坏输入数据。如果您不知道如何将输出保存到文件;请问)。我看到有人赞成你的评论。是不是表示存在jq不起作用的环境?
  • 为了您的方便jq ... INPUT > INPUT.tmp && mv INPUT.tmp INPUTstackoverflow.com/questions/36565295/…
猜你喜欢
  • 1970-01-01
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-02
相关资源
最近更新 更多