通过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 如的 JQ
- 在基于Debian的系统,如Ubuntu,你可以通过
命令和apt-get安装JQ
安装
- 在OSX,用自制( http://brew.sh/ ),使用
酿造安装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
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20