How to delete a key value pair from JSON response, goovy script
I have a groovy which basically make a rest request as below sample and returns JSON response. but in the response returned i would like to remove a key value pair(IsEditable = true) before i start comparing to DB values as we don't stoe that in DB. How do i find a key and remove the key before i start doing the DB compare step . Any sample code to look at on how we can remove the key ?
// Use the json slurper class method to read the API response values
def Response = context.expand( '${Validate Pparam #Response}' )
def slurperResponse = new JsonSlurper().parseText(Response)
def sortedJSON = slurperResponse.data.sort { a,b -> b.PCode<=> a.PCode}
log.info("API Response results:" + sortedJSON)
Response returned :
{
"PVOptions" : "Yes, No",
"UCount" : 449,
"PName" : "Affordable Price All",
"IsEdit" : true,
"PCode" : "1234",
"PPId" : 984,
"IPNullable" : false
}
But i would like my response to be returning as below . How do i acheive this ? :("IsEdit" : true should not get returned)
{
"PVOptions" : "Yes, No",
"UCount" : 449,
"PName" : "Affordable Price All",
"PmCode" : 347,
"PCode" : "1234",
"PParameterId" : 984,
"IPNullable" : false
}
The JsonSlurper returns Maps and Lists, thus with your second example you need to loop through each List item, which in turn is a Map and remove the item from each, for example:
import groovy.json.JsonSlurper def Response = '''\ [{ "PVOptions" : "Yes, No", "UCount" : 449, "PName" : "Affordable Price All", "IsEdit" : true, "PCode" : "1234", "PPId" : 984, "IPNullable" : false }, { "PVOptions" : "Yes, No", "UCount" : 4495, "PName" : "Affordable Price All", "IsEdit" : true, "PCode" : "12345", "PPId" : 984, "IPNullable" : false }] ''' def slurperResponse = new JsonSlurper().parseText(Response) log.info("API Response results:" + slurperResponse.toString()) slurperResponse.each(){ dataSet -> dataSet.remove('IsEdit') } log.info("API Response results:" + slurperResponse.toString())