Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

bash

shell

jq

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?

like image 266
pun Avatar asked Dec 06 '25 05:12

pun


1 Answers

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"
like image 81
Jeff Mercado Avatar answered Dec 07 '25 19:12

Jeff Mercado