jq有条件更新数组元素

时间:2018-09-04 16:55:33

标签: json if-statement edit jq

我想根据同一数组中另一个元素的值有条件地更新一个元素值。

例如,我要查找name ==“ weather”并将选中的内容从“ true”更改为“ false”

[
  {
    "originalSourceId": null,
    "sourceConnection": {
      "id": null,
      "version": null,
      "properties": [
        {
          "id": null,
          "version": null
        }
      ],
      "name": "POSTGRESQL",
      "businessName": null
    },
    "checked": true,
    "newlyAdded": false,
    "discoveredEntities": [
      {
        "name": "weather",
        "checked": true,
        "checkedBeforeEdit": false,
        "storeFieldsAsStrings": false
      },
      {
        "name": "weather_2",
        "checked": true,
        "checkedBeforeEdit": false,
        "storeFieldsAsStrings": false
      }
    ],
    "defaultLevel": "MANAGED"
  }
]

同一名称为“ weather”的对象的选中元素将更新为“ false”

[
  {
    "originalSourceId": null,
    "sourceConnection": {
      "id": null,
      "version": null,
      "properties": [
        {
          "id": null,
          "version": null
        }
      ],
      "name": "POSTGRESQL",
      "businessName": null
    },
    "checked": true,
    "newlyAdded": false,
    "discoveredEntities": [
      {
        "name": "weather",
        "checked": false,
        "checkedBeforeEdit": false,
        "storeFieldsAsStrings": false
      },
      {
        "name": "weather_2",
        "checked": true,
        "checkedBeforeEdit": false,
        "storeFieldsAsStrings": false
      }
    ],
    "defaultLevel": "MANAGED"
  }
]

3 个答案:

答案 0 :(得分:1)

对于这些类型的更新,如果您这样想,则更容易直观地看到它们,先找到要更新的项目,然后再进行更新。

 (.[].discoveredEntities[] | select(.name == "weather").checked) = false
#[ locate the items to update                         ]
#                                                      [ update them   ]

答案 1 :(得分:0)

弄清楚了。

jq '[.[].discoveredEntities[] |= if (.name=="weather") then (.checked = "false") else . end]'\
    ./test.json

答案 2 :(得分:0)

在这里使用map会产生一个非常简单的解决方案:

map( .discoveredEntities |=
        map(if .name == "weather" then .checked = false else . end))

请注意,显然在这里使用false"false"更合适。