Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

How do I update a single value in a json document using jq?

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.

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 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.

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

{
  "shipping": {
    "local": true,
    "us": true,
    "us_rate": {
      "amount": "0.00",
      "currency": "USD",
      "symbol": "$"
    }
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...