Home > Net >  modify json with jq
modify json with jq

Time:10-11

I would like to use JQ to modify the following JSON input:

[
  {
    "description": "",
    "created_on": "2021-12-27T11:32:03.171682Z",
    "modified_on": "2021-12-27T11:32:03.171682Z",
    "id": "test",
    "enabled": true,
    "minimum_origins": 1,
    "monitor": "test",
    "name": "test",
    "notification_email": "",
    "check_regions": null,
    "latitude": 43.7417,
    "longitude": -79.3733,
    "notification_filter": {
      "pool": {}
    },
    "healthy": true,
    "origins": [
      {
        "name": "AAAA",
        "address": "1.1.1.1",
        "enabled": true,
        "weight": 1,
        "healthy": true,
        "failure_reason": "No failures"
      },
      {
        "name": "BBBB",
        "address": "2.2.2.2",
        "enabled": true,
        "weight": 1,
        "healthy": true,
        "failure_reason": "No failures"
      }
    ]
  }
]

if address == 1.1.1.1 then weight 0

that's what i expect

[
  {
    "name": "test",
    "origins": [
      {
        "name": "AAAA",
        "address": "1.1.1.1",
        "enabled": true,
        "weight": 0,
        "healthy": true,
        "failure_reason": "No failures"
      },
      {
        "name": "BBBB",
        "address": "2.2.2.2",
        "enabled": true,
        "weight": 1,
        "healthy": true,
        "failure_reason": "No failures"
      }
    ]
  }
]

my best attempt but it doesn't fit my format. I tried many different options but could not find the correct code

(.[].origins[] | select(.address == "1.1.1.1") | .weight ) |= 0

CodePudding user response:

Here's a slightly different version, but pmf's answer is preferable.

map({
    name,
    origins: .origins | map(select(.address=="1.1.1.1").weight = 0)
})

CodePudding user response:

Either perform setting the value first (where you could simply use = to set the new value as it does not depend on the old one), then use map({name, origins}) to get your expected output reduction:

(.[].origins[] | select(.address == "1.1.1.1")).weight = 0
| map({name, origins})

Demo

Or combine both within the map in one go:

map(
  {name, origins}
  | .origins[] |= (select(.address == "1.1.1.1").weight = 0)
)

Demo

Output:

[
  {
    "name": "test",
    "origins": [
      {
        "name": "AAAA",
        "address": "1.1.1.1",
        "enabled": true,
        "weight": 0,
        "healthy": true,
        "failure_reason": "No failures"
      },
      {
        "name": "BBBB",
        "address": "2.2.2.2",
        "enabled": true,
        "weight": 1,
        "healthy": true,
        "failure_reason": "No failures"
      }
    ]
  }
]
  • Related