• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

通过bash脚本更改JSON文件

用户头像
it1352
帮助1

问题说明

我需要你的帮助解决以下问题:
我有一个JSON文件看起来像这样:

I need your help to solve the following problem: I have a JSON file that looks like this:

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

我怎么可以添加和删除一个新的密钥(即KEY4:VALUE4)由bash脚本?
我也看到了这个问题,添加或添加或删除新的之前删除的文件中的最后一个关键的最后一个逗号。

how can I add and remove a new key (i.e "key4": "value4") by bash script? I see also the issue to add or remove a comma at the end of last key in the file before adding or removing the new one.

感谢您

正确答案

#1

您的最好的办法是使用JSON CLI JQ

    • 在基于Debian的系统,如Ubuntu,你可以通过命令和apt-get安装JQ
    • 安装
  • On Debian-based systems such as Ubuntu, you can install it via sudo apt-get install jq
  • On OSX, with Homebrew (http://brew.sh/) installed, use brew install jq

例如,基于以下输入字符串 - 输出是标准输出

Examples, based on the following input string - output is to stdout:

jsonStr='{ "key1": "value1", "key2": "value2", "key3": "value3" }'

删除KEY3:

jq 'del(.key3)' <<<"$jsonStr"

添加属性KEY4与价值VALUE4:

jq '.   { "key4": "value4" }' <<<"$jsonStr"

如果你想的更新代替JSON文件(从概念上讲),使用删除KEY3的例子:


If you want to update a JSON file in place (conceptually speaking), using the example of deleting "key3":

# Create test file.
echo '{ "key1": "value1", "key2": "value2", "key3": "value3" }' > test.json

# Remove "key3" and write results back to test.json (recreate it with result).
jq -c 'del(.key3)' test.json > tmp.$$.json && mv tmp.$$.json test.json

您不能直接替换输入文件,所以结果被写入替换成功输入文件的临时文件。

You cannot replace the input file directly, so the result is written to a temporary file that replaces the input file on success.

请注意在 -c 选项,产生紧凑,而不是pretty印刷JSON。

Note the -c option, which produces compact rather than pretty-printed JSON.

对于所有选项和命令,看到手动是在 HTTP: //stedolan.github.io/jq/manual/

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcficgg
系列文章
更多 icon
同类精品
更多 icon
继续加载