Vini
Vini

Reputation: 2134

Replacing the value of JSON based on key value pair with jq

I have a JSON with the following structure

{
   "name": "name",
   "id": [
        "abcdef"
   ],
   "input_dataobjects": [
     {
        "id": "someid1",
        "name": "somename1",
        "provider": "someprovider",
        "datatype": "somedatatype1"
    },
    {
        "name": "some_name2",
        "datatype": "some_datatype2",
        "id": "some_id2"
    }
  ]
}

What I am trying to achieve

in input_dataobjects if datatype == somedatatype1 then name = sonemewname1.

I can use the index of the input_dataobjects since my json always has the same structure. But is there any different way to achieve it by parsing through the input_dataobjects and find the index to replace? I am using jq to do JSON operations.

I tried with using the index like .input_dataobjects[0].name="someting" because i know the position of the datatype always.

Upvotes: 0

Views: 191

Answers (1)

peak
peak

Reputation: 116740

The simplest and perhaps most efficient solution to the problem as stated is:

.input_dataobjects |=
  map( if .datatype == "somedatatype1"
       then .name = "sonemewname1"
       else . end )

Upvotes: 4

Related Questions