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

前端 未结 3 1898
离开以前
离开以前 2020-12-01 06:11

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 da

3条回答
  •  长情又很酷
    2020-12-01 06:27

    a similar function to the operator |= is map. map will be suitable to avoid the requirement of a previous filter for the array...

    imagine that your data is an array (very common for this example)

    [
      {
        "shipping": {
          "local": true,
          "us": true,
          "us_rate": {
            "amount": "1.00",
            "currency": "USD",
            "symbol": "$"
          }
        }
      },
      {
        "shipping": {
          "local": true,
          "us": true,
          "us_rate": {
            "amount": "1.00",
            "currency": "USD",
            "symbol": "$"
          }
        }
      }
    ]
    

    hence it is necessary to consider the array in the code as:

    http://example.com/shipping.json | jq '.[] | .shipping.local = "new place"' | curl -X PUT http://example.com/shipping.json
    

    or to use the map function that is crafted to work in every array element as

    http://example.com/shipping.json | jq 'map(.shipping.local = "new place")' | curl -X PUT http://example.com/shipping.json
    

    Observation

    For the sake of those that are learning, you also did some mistakes in the jq usage, just consider that it does "read" the 1st parameter as the program, hence all the desired commands shall be included in the very first string after calling the program.

提交回复
热议问题