【问题标题】:is it possible to modify json objects in CLI?是否可以在 CLI 中修改 json 对象?
【发布时间】:2016-02-02 15:20:27
【问题描述】:

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

{ "mykey" :"myvalue"}

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

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

我知道我可以很容易地想出 Python 脚本来做到这一点。在 CLI 中有没有更简单的方法来做到这一点?类似的东西

   addjson "newkey" "newvalue" myfile*.json

【问题讨论】:

    标签: python json linux bash command-line-interface


    【解决方案1】:

    您可以使用 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/

    【讨论】:

      【解决方案2】:

      为此使用jq

      添加键值对:

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

      有关jq 的更多信息,请参阅manualCookbook

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-27
        • 2014-10-28
        • 1970-01-01
        • 1970-01-01
        • 2021-10-31
        • 2023-04-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多