pun
pun

Reputation: 111

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?

Upvotes: 3

Views: 2726

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134601

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"

Upvotes: 6

Related Questions