Home > Enterprise >  Groovy Modifying Json
Groovy Modifying Json

Time:11-10

I'm trying to modify a json which I'm reading from a file:

String response = new File("response.json").text

here is what response looks like:

{
  "TerminatingInstances": [
    {
      "InstanceId": "id",
      "CurrentState": {
        "Code": 32,
        "Name": "shutting-down"
      },
      "PreviousState": {
        "Code": 16,
        "Name": "running"
      }
    }
  ]
}

To modify it I did as follows:

def slurped = new JsonSlurper().parseText(response)
def builder = new JsonBuilder(slurped)
builder.content.TerminatingInstances.InstanceId = "id-updated"

but I get argument type mismatch error, not sure why.

CodePudding user response:

That's because it's an array of instances inside TerminatingInstances

You can either set all of them to the new id with *.:

builder.content.TerminatingInstances*.InstanceId = "id-updated"

Or set just the first one with

builder.content.TerminatingInstances[0].InstanceId = "id-updated"
  • Related