是否可以在 CLI 中修改 json 个对象?

is it possible to modify json objects in CLI?

我有数千个包含 JSON 个对象的文件 比如

{ "mykey" :"myvalue"}

而且我必须在每个文件中添加一个键值对 例如

{ "mykey" :"myvalue", "newkey": "newvalue"}

我知道我可以很容易地想出 Python 脚本来完成它。在 CLI 中有更简单的方法吗?像

   addjson "newkey" "newvalue" myfile*.json

为此使用 jq

添加键值对:

echo '{ "mykey" :"myvalue"}' | jq '. + {"newkey":"newvalue"}'

有关 jq 的更多信息,请参阅 manual and Cookbook

您可以使用 json node.js 模块。 获得 node.js 后,您可以使用 sudo npm install -g json

安装它

用法json -I -f myfile.json -e 'this.newkey="newvalue"'

同时只能有一个文件,但是正如你所说,你可以使用python 或 bash 中带有 for 循环的示例:for i in $(ls myfile*.json); do json -I -f $i -e 'this.newkey="newvalue"'; done

文档:http://trentm.com/json/