本文介绍了通过bash脚本更改JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要你的帮助解决以下问题:
我有一个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.

感谢您

推荐答案

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


  • 在基于Debian的系统,如Ubuntu,你可以通过命令和apt-get安装JQ
  • 安装
    安装
  • 在OSX,用自制(),使用酿造安装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.

对于所有选项和命令,看到手动是在。

这篇关于通过bash脚本更改JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 09:03