Forum Discussion

TomA's avatar
TomA
New Contributor
12 months ago
Solved

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###"

3 Replies

  • nmrao's avatar
    nmrao
    Champion Level 3

    You can try the below

    json.cEntity.references.find{it.name == 'ID_ONE'}.userValue = "newID_ONE###"
    • TomA's avatar
      TomA
      New Contributor

      Great solution. Is there a reason you can see my original approach should not have worked? Seems to work outside of ReadyAPI.

      • nmrao's avatar
        nmrao
        Champion Level 3
        It was working outside as the json content is static as you are updating based on index.

        In the solution provided, find the name whose value provided and update it's value. So, the position is not considered to update.