选择条件后向 JSON 对象添加记录

Adding a record to JSON object after selecting on a condition

我有以下 json:

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

我想将以下 {default: yes} 添加到我 select 的内容中。

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

我有以下但还没想好怎么添加记录

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

我试过了. += {default: yes}| . += {default: yes}|= . +但是我走错了路

谢谢

将引号 " 放在您要搜索的数字类型上。引号仅适用于 selecting/matching 字符串类型。

使用+=在所选条目上添加对象

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

jqplay 演示 - https://jqplay.org/s/k5tForQ9HT


如果您要将匹配标识符作为参数传递,请参考处的答案,因为--arg默认将您的参数定义为字符串类型,需要修改你里面的 select 以数字类型进行比较。所以使用 $thermoid|tonumber 或将其作为 argjson

传递