I have the following JSON:
{"name":"Guillaume","age":33,"address":"main st","pets":[{"type":"dog", "color":"brown"},{"type":"dog", "color":"brown"}]}}
I have used JsonSlurper to parse it. I have a need to be able to modify the contents of the JSON based on various criteria. The keys I want to modify are externally defined.
I can easily change a string value as follows. The below results in the address field in the lazyMap being changed from "main st" to "second st".
import groovy.json.JsonSlurper
def slurper = new JsonSlurper()
def result = slurper.parseText('{"person": {"name":"Guillaume","age":33,"address":"main st","pets":[{"type":"dog", "color":"brown"},{"type":"dog", "color":"brown"}]}}')
String address = "result.person.address" // Note: this is externalized
String newAddressValue = "second st"
Eval.me('result', result, "$address = '$newAddressValue'")
println result.person.address
The problem I can't seem to solve is if I want to change the address value from a string to a map.
import groovy.json.JsonSlurper
def slurper = new JsonSlurper()
def result = slurper.parseText('{"person": {"name":"Guillaume","age":33,"address":"main st","pets":[{"type":"dog", "color":"brown"},{"type":"dog", "color":"brown"}]}}')
Map newAddressMap = slurper.parseText(/{"street":"Third Street", "city":"New York", "state":"New York"}/)
Eval.me('result', result, "$address = $newAddressMap")
println result.person.address.getClass()
println result.person.address
The $newAddressMap above is interpreted as a string resulting in the following error:
startup failed: Script1.groovy: 1: The current scope already contains a variable of the name York @ line 1, column 51. s = [city:New York, state:New York, stre
However, the below works (changes the address key value from a String to a LazyMap), but requires my key to be known/hard-coded:
result.person.address = newAddressMap
println result.person.address.getClass()
println result.person.address
The below does not error, but the $newAddressMap is a string and the lazyMap key "address" remains a string.
Eval.me('result', result, "$address = '$newAddressMap'")
println result.person.address.getClass()
println result.person.address
How can I change the address key value from a String to a Map while having the address key value defined at runtime?