【问题标题】:How to add a field to a JSON object with the jq command?如何使用 jq 命令向 JSON 对象添加字段?
【发布时间】:2018-04-03 14:24:50
【问题描述】:

我有这个 JSON 数据:

{
    "success": true,
    "module": {
        "data": {
            "item_i77f664a2": {
                "id": "i77f664a2",
                "tag": "item",
                "fields": {
                    "cartItemId": 2012636322
                },
                "type": "biz"
            }
        }
    }
}

我想在cartItemId 正下方添加{"operation":"delete"},然后将JSON 数据保存到文件中。我想要的结果是这样的:

{
    "success": true,
    "module": {
        "data": {
            "item_i77f664a2": {
                "id": "i77f664a2",
                "tag": "item",
                "fields": {
                    "cartItemId": 2012636322,
                    "operation": "delete"
                },
                "type": "biz"
            }
        }
    }
}

这是我尝试过的:

jq '.module.data.item_i77f664a2.fields + {"operation":"delete"}' > data.json

但它不会像上面那样将 JSON 数据与我想要的输出一起保存。我该如何解决?

【问题讨论】:

    标签: json jq


    【解决方案1】:

    这种类型的更新正是+= 的魔力发挥作用的地方。根据您的输入,以下调用:

    jq '.module.data.item_i77f664a2.fields += {"operation":"delete"}'
    

    产生你想要的输出:

    {
      "success": true,
      "module": {
        "data": {
          "item_i77f664a2": {
            "id": "i77f664a2",
            "tag": "item",
            "fields": {
              "cartItemId": 2012636322,
              "operation": "delete"
            },
            "type": "biz"
          }
        }
      }
    }
    

    但是,我不确定这是否会在类似情况下产生您想要的结果,因为您引用了“item_i77f61ee2”。

    【讨论】:

    • 这个附加在最后,如何在最前面而不是最后插入?
    • @karthik101 - '.module.data.item_i77f664a2.fields |= [{"operation":"delete"}] + .'
    • @peak 不会只是合并两者吗?您能否具体指定“在属性cartItemId 之后添加此新属性?(例如,假设有许多fields 而不是只有一个。
    • @JoshM - + 是多态的:它既可用于对象的合并,也可用于数组的串联等。如果这不能回答您的问题,也许您会想问一个新的 SO 问题 ...
    【解决方案2】:

    感谢@peak 的回答!

    只想补充,

    创建一个空白的 json 文件:

    echo "{}" > config.json
    

    文件内容:

    {}
    

    然后在文件中添加属性:

    echo "$(jq '. += {"url": "https://url.com"}' config.json)" > config.json
    

    文件内容:

    {
        "url": "https://url.com"
    }
    

    还有一个属性:

    echo "$(jq '. += {"name": "a Name"}' config.json)" > config.json
    

    文件内容:

    {
        "url": "https://url.com",
        "name": "a Name"
    }
    

    如果您设置了变量并希望使用该值(即 Azure Build Pipelines),您可以将该值作为参数传递(在这种情况下为urlarg):

    URL="https://url.com"
    echo "$(jq --arg urlarg "$URL" '. += {"url": $urlarg}' config.json)" > config.json
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-27
      • 2014-05-16
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 2022-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多