简体   繁体   中英

bash JQ. How can modify a key value pair from json file containing list of objects?

I am using jq to work on a large json file. It looks something like this:

FILE1.json

{
  "person": [
      {
          "name": "sam",
          "age": "40",
          "weight": "180",
          "height": "6"
       },
       {
          "name": "peter",
          "age": "41",
          "weight": "180",
          "height": "6.1"
       },
       {
          "name": "mike",
          "age": "40",
          "weight": "200",
          "height": "5.9"
       },
       {
          "name": "ethan",
          "age": "41",
          "weight": "190",
          "height": "6"
       }
  ]
}

I want to use jq tool to change the value of weight from 200 to 195 where name is "mike".
How can i do this?

The idea is to update the person array where the object that has the name "mike" will be modified to have the weight "195" . Otherwise it's just skipped.

.person |= map(
    if .name == "mike"
        then .weight = "195"
        else .
    end)

Or more concisely, search for the persons to update and update them:

(.person[] | select(.name == "mike")).weight = "195"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM