如何使用jq在json文档中更新单个值?

时间:2021-09-27 07:08:38

Appologies if I've overlooked something very obvious; I've just found jq and am trying to use it to update one JSON value without affecting the surrounding data.

如果我忽略了一些很明显的东西;我刚刚找到了jq,并试图使用它更新一个JSON值,而不影响周围的数据。

I'd like to pipe a curl result into jq, update a value, and pipe the updated JSON to a curl -X PUT. Something like

我想将一个curl结果导入到jq中,更新一个值,并将更新后的JSON传输到一个curl -X PUT中。类似的

curl http://example.com/shipping.json | jq '.' field: value | curl -X PUT http://example.com/shipping.json

So far I've hacked it together using sed, but after looking at a few examples of the |= operator in jq I'm sure that I don't need these.

到目前为止,我已经使用sed将它合并到一起,但是在查看了jq中|=操作符的一些示例之后,我确信我不需要这些。

Here's a JSON sample--how would I use jq to set "local": false, while preserving the rest of the JSON?

这里有一个JSON示例——我如何使用jq来设置“local”:false,同时保留JSON的其余部分?

{
  "shipping": {
    "local": true,
    "us": true,
    "us_rate": {
      "amount": "0.00",
      "currency": "USD",
      "symbol": "$"
    }
  }
}

1 个解决方案

#1


56  

You set values of an object using the = operator. |= on the other hand is used to update a value. It's a subtle but important difference. The context of the filters changes.

使用=运算符来设置对象的值。另一方面,|=用于更新值。这是一个微妙但重要的区别。过滤器的上下文会发生变化。

Since you are setting a property to a constant value, use the = operator.

由于您将属性设置为一个常量值,请使用=操作符。

.shipping.local = false

Just note that when setting a value to a property, it doesn't necessarily have to exist. You can add new values easily this way.

只需注意,当为属性设置值时,它不一定存在。您可以通过这种方式轻松地添加新值。

.shipping.local = false | .shipping.canada = false | .shipping.mexico = true

#1


56  

You set values of an object using the = operator. |= on the other hand is used to update a value. It's a subtle but important difference. The context of the filters changes.

使用=运算符来设置对象的值。另一方面,|=用于更新值。这是一个微妙但重要的区别。过滤器的上下文会发生变化。

Since you are setting a property to a constant value, use the = operator.

由于您将属性设置为一个常量值,请使用=操作符。

.shipping.local = false

Just note that when setting a value to a property, it doesn't necessarily have to exist. You can add new values easily this way.

只需注意,当为属性设置值时,它不一定存在。您可以通过这种方式轻松地添加新值。

.shipping.local = false | .shipping.canada = false | .shipping.mexico = true