Adding a record to JSON object after selecting on a condition

Viewed 74

I have the following json:

{
   "thermostats": [
      {
         "name": "Thermostat1",
         "identifier": 111111111111
      },
      {
         "name": "Thermostat2",
         "identifier": 222222222222
      }
   ]
}

I'd like to add the following {default: yes} to the one that I select.

{
   "thermostats": [
      {
         "name": "Thermostat1",
         "identifier": 111111111111,
         "default": "yes"
      },
      {
         "name": "Thermostat2",
         "identifier": 222222222222
      }
   ]
}

I have the following but haven't figured out how to add the record

q '.thermostats[] | select (.identifier == "1111111111")

I've tried . += {default: yes} | . += {default: yes} |= . + but I'm going off the wrong track.

Thanks

1 Answers

Drop the quote marker " on the numeric type you are trying to search. Quotes should apply only when selecting/matching string types.

Use += to add the object on the selected entry

(.thermostats[] | select(.identifier == 111111111111)) += {default: "yes"}

jqplay demo - https://jqplay.org/s/k5tForQ9HT


If you were to pass the match identifier as an argument, do refer to the answers at Numeric argument passed with jq --arg not matching data with ==, because --arg by default defines your argument to be string type, which needs to be modified inside your select to numeric type for comparison. So use $thermoid|tonumber or pass it as argjson

Related