jsonjq

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": "$"
    }
  }
}

Solution

  • You set values of an object using the = operator. |= on the other hand is used to update a value. Use |= if you need to know the current value of the property, it will be passed as the input (.) on your right hand side (if set). Using = on the other hand does not set the input at all for the RHS, it will simply be null. It's a subtle but important difference. The context of the RHS 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