在bash中操纵JSON

我有一个JSON文件,我需要更新一个特定的值。

{ "Comment": "comment", "test": { "enabled": true }, "enabled": true, "otherStuff": blah, "otherStuff2": blah, "otherStuff3": blah, } 

我想将第二个“启用”的值更改为false。 使用JQ Parser,我可以使用jq'.enabled '轻松地检索它,但我不确定操纵JSON的最佳方式是什么。

JSON是我从API获取的响应,将来可能会发生变化,我不能依赖前面的行或值。

一个快速的实验:

 $ echo '{ "Comment": "comment", "test": { "enabled": true }, "enabled": true, "otherStuff": "blah", "otherStuff2": "blah", "otherStuff3": "blah" }' | jq '.enabled=false' 
 { "otherStuff3": "blah", "otherStuff2": "blah", "otherStuff": "blah", "enabled": false, "test": { "enabled": true }, "Comment": "comment" } 

我把这个问题看成是“在shell中”而不是“只用bash builtins”。

试试jsawk ,它允许操纵和脚本,认为它依赖于js作为依赖。

如果你只想从JSON响应中读取一个(唯一的)键,你可以(改编自Brendan OConnor ):

 curl <destination> | grep -Po '"keyname":.*?[^\\]",'`