Performing a JsonPath replacement in groovy
The following code works in a groovy step, but if you notice, I am replacing an element by hard position referencing i.e. references[0]:
json.cEntity.references[0].userValue = "newID_ONE###"
import groovy.json.*
def myJsonString= '''{
"Invoice": {
"number": "Test_9Sept"
},
"cEntity": {
"type": "Carton",
"references": [
{
"name": "ID_ONE",
"userValue": "ID_ONE00004"
},
{
"name": "E_ID",
"userValue": "eid-1234"
}
],
"attributes": [
{
"name": "PART_NO",
"userValue": "123456789"
}
]
}
}'''
def json = new JsonSlurper().parseText(myJsonString)
json.cEntity.references[0].userValue = "newID_ONE###"
return (JsonOutput.toJson(json))
My goal is to replace the value of userValue for the references block which has name of "ID_ONE" by using a JSONPath Expression such as:
$.cEntity.references[?(@.name=='ID_ONE')].userValue = '9999'
Example, line which currently reads:
json.cEntity.references[0].userValue = "newID_ONE###"
becomes
json.cEntity.references[?(@.name=='ID_ONE')].userValue = '9999'
Based on the reading I have done this should work, but does not when I put it into the groovy step.
For reference:How to change values json groovy - Stack Overflow
You can try the below
json.cEntity.references.find{it.name == 'ID_ONE'}.userValue = "newID_ONE###"