Need help on replacing JSON field with constant String in Groovy - groovy

I want to replace a JSON field - JSONtoReplace by the below JSON strings
[{"RoleName": "Normal User","ModuleName": "Calendar Management"},
{"RoleName": "Reporter","ModuleName": "Incident Management"},
{"RoleName": "Viewer","ModuleName": "ESG"},
{"RoleName": "Viewer","ModuleName": "Apps"}]
Source JSON BODY
{"PersonInformation":{"EmailAddress":"fabian.koehlmann#atotech.com","Name":{"FirstName":"Fabian","LastName":"KOEHLMANN","PreferredName":"Fabian Köhlmann"},"Address":{"AddressLine1":"Berlin GmbH","AddressLine2":"Erasmusstraße 20,,,,,","PostalCode":"10553"},"employeeInformation":{"EmployeeType":"internal","EmploymentStatus":"Active","JobRole":{"Department":"Finance - IT","IsCreateDepartment":"null","JobTitle":"Specialist IT Security & Infrastructure","SupervisorId":"null","StartDate":"09/29/2021","EffectiveDate":"null"},"Location":"Berlin GmbH","Occupation":"null"},"IsUser":"true","UserInformation":{"UserId":"7fa1785f-f4f3-42b5-96bd-33f195521635","Status":"active","Locations":{"Scope":"TRN-LOC","Roles":"JSONtoReplace"}},"RecordUid":"2022/05/27","Id":"A0201412"}}
Groovy Script
def Message processData(Message message) {
def body = message.getBody(java.lang.String) as String;
def jsonSlurper = new JsonSlurper()
def SourceBody = jsonSlurper.parseText(body)
def ReplaceData = jsonSlurper.parseText('[{"RoleName": "Normal User","ModuleName":
"Calendar Management"},{"RoleName": "Reporter","ModuleName": "Incident Management"},
{"RoleName": "Viewer","ModuleName": "ESG"},{"RoleName": "Viewer","ModuleName":
"Apps"}]')
body = body.replaceAll('JSONtoReplace','ReplaceData');
message.setBody(body);
return message;
}

I want to replace a JSON field
You can do something like this:
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
// ...
// This hardcoded String represents "body" from the code in the question
String jsonString = '''
[{"RoleName": "Normal User","ModuleName": "Calendar Management"},
{"RoleName": "Reporter","ModuleName": "Incident Management"}]
'''
def slurper = new JsonSlurper()
def json = slurper.parseText(jsonString)
println 'Before Update...'
println new JsonBuilder(json).toPrettyString()
json[0].'RoleName' = 'Updated'
println 'After Update...'
println new JsonBuilder(json).toPrettyString()
The output:
Before Update...
[
{
"RoleName": "Normal User",
"ModuleName": "Calendar Management"
},
{
"RoleName": "Reporter",
"ModuleName": "Incident Management"
}
]
After Update...
[
{
"RoleName": "Updated",
"ModuleName": "Calendar Management"
},
{
"RoleName": "Reporter",
"ModuleName": "Incident Management"
}
]

Related

How to do a POST web api call with groovy code?

I have some POST method url, 2 headers to pass and a big body in Json format, that I need to call through the Groovy code. But I am not sure on points like how to pass headers and big Json object in Groovy code for API call. Please help me on thease points. I am writin this code in visual code.
Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1' )
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
def post = new URL("https://xyxz/api/testRequest/generic").openConnection();
def message = '{
"test": "test",
"test1": "test1\n\t",
"test2": {
"test3": "test3",
"test4": "test4"
}'
post.setRequestMethod("POST")
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.setHeader("id","sadasdas1212134");
post.setHeader("id2","sdsd34sdsfdfdfdf");
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if(postRC.equals(200)) {
println(post.getInputStream().getText());
}
Straight from the ref-doc
import groovyx.net.http.HttpBuilder
def body = [
"test": "test",
"test1": "test1\n\t",
"test2": [
"test3": "test3",
"test4": "test4"
]
]
def result = HttpBuilder.configure {
request.uri = 'https://xyxz/api/testRequest/generic'
request.headers.id = 'sadasdas1212134'
request.headers.id2 = 'sdsd34sdsfdfdfdf'
request.contentType = 'application/json'
request.body = body
}.post()
println result

Generate json body using groovy in jmeter having array inside an array

I'm trying to generate JSON body dynamically using values in csv file. For this i'm making use of JSR223 PreProcessor with groovy script.
I'm expecting the below format to be generate when i run the groovy script
{
"transactionId": "100",
"lineItems": [{
"lineItemNo": "1",
"cardInfo": {
"cardNumber": "3456"
}
},
{
"lineItemNo": "2",
"cardInfo": {
"cardNumber": "45698"
}
}
]
}
but when i execute script i'm getting below format
POST data:
{
"transactionId": "100",
"lineItems": [
{
"lineItemNo": "1",
"Cardinfo": [
9255000012794606,
9255000012794645
]
},
{
"lineItemNo": "1",
"Cardinfo": [
9255000012794606,
9255000012794645
]
}
]
}
Script to generate json body
File csvFile = new File("D:\\Project Related Docs\\Jmeter\\apache-jmeter-5.0\\bin\\Map_Performance\\Map_New_Auto_jmx\\2Cards.csv")
def cards = csvFile.readLines()
List<String> cardnumbmer = new ArrayList<>()
def counter = 1
cards.eachWithIndex{line,idx->cardnumbmer.add(line)}
log.info("size of csv = "+cardnumbmer.size())
log.info("File conents = "+cardnumbmer[0])
//build the json body
def ids = new groovy.json.JsonSlurper().parseText(cardnumbmer.toString())
log.info("cardnumbmer to string = "+cardnumbmer.toString())
def builder = new groovy.json.JsonBuilder()
builder([
transactionId:"100",
lineItems:ids.collect{[lineItemNo:"1",Cardinfo: ids.collect{carnumber: it}]}
])
//sampler.getArguments().removeAllArguments()
sampler.addNonEncodedArgument('',builder.toPrettyString(),'')
sampler.setPostBodyRaw(true);
--CSV FILE have cardnumbers listed in row-wise look like below
9255000012794606
9255000012794645
Request to help me to know how to fix this issue.
ids.collect{carnumber: it} is basically ids. Be explicit about returning the map: ids.collect{ [carnumber: it] }
Below code resolved the problem
//build the json body
def ids = new groovy.json.JsonSlurper().parseText(cardnumbmer.toString())
log.info("cardnumbmer to string = "+cardnumbmer.toString())
def builder = new groovy.json.JsonBuilder()
def count = 1
builder([
transactionId:"100",
//lineItems:ids.collect{[lineItemNo:"1",Cardinfo: count.collect{[carnumber: it]}]}
lineItems:ids.collect{[lineItemNo:count++,Cardinfo: [Cardnumber:it]]}
])
//sampler.getArguments().removeAllArguments()
sampler.addNonEncodedArgument('',builder.toPrettyString(),'')
sampler.setPostBodyRaw(true);

How to format rest Json response in soapUI?

I am getting JSON body from REST response with escaped characters shown below. How to format JSON response in soapUI using groovy script?
From:
{
"employee": "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"
}
To:
{ "employee": {
"name": "John",
"age": 30,
"city": "New York" } }
A simple string-replace would do the job:
def escapedString = '''{"employee":"{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"}'''
def unescapedString = escapedString.replaceAll("\\\\", "")
System.out.println unescapedString
This produces:
{"employee":"{"name":"John", "age":30, "city":"New York"}"}

Parsing child nodes of JSON response in SOAP UI using groovy json slurper

I am getting a JSON response from an webservice like below . I want to parse all childs of results node using Groovy Json slurper and assert the value is correct.
{
"status": "Healthy",
"results": [
{
"name": "Microservice one",
"status": "Healthy",
"description": "Url check MSOneURI success : status(OK)"
},
{
"name": "Microservice two",
"status": "Healthy",
"description": "Url check MSTwoURI success : status(OK)"
},
{
"name": "Microservice three",
"status": "Healthy",
"description": "Url check MSThreeURI success : status(OK)"
},
{
"name": "Microservice four",
"status": "Healthy",
"description": "Url check MSFourURI success : status(OK)"
},
{
"name": "Microservice five",
"status": "Healthy",
"description": "Url check MSFiveURI success : status(OK)"
}
]
}
This is what I have done - this works .
//imports
import groovy.json.JsonSlurper
import groovy.json.*
//grab the response
def ResponseMessage = messageExchange.response.responseContent
// trim starting and ending double quotes
def TrimResponse =ResponseMessage.replaceAll('^\"|\"$','').replaceAll('/\\/','')
//define a JsonSlurper
def jsonSlurper = new JsonSlurper().parseText(TrimResponse)
//verify the response to be validated isn't empty
assert !(jsonSlurper.isEmpty())
//verify the Json response Shows Correct Values
assert jsonSlurper.status == "Healthy"
def ActualMsNames = jsonSlurper.results*.name.toString()
def ActualMsStatus = jsonSlurper.results*.status.toString()
def ActualMsDescription = jsonSlurper.results*.description.toString()
def ExpectedMsNames = "[Microservice one,Microservice two,Microservice three,Microservice four,Microservice five]"
def ExpectedMsStatus = "[Healthy, Healthy, Healthy, Healthy, Healthy]"
def ExpectedMsDescription = "[Url check MSOneURI success : status(OK),Url check MSTwoURI success : status(OK),Url check MSThreeURI success : status(OK),Url check MSFourURI success : status(OK),Url check MSFiveURI success : status(OK)]"
assert ActualMsNames==ExpectedMsNames
assert ActualMsStatus==ExpectedMsStatus
assert ActualMsDescription==ExpectedMsDescription
But I want to make it better using some kind of for loop which will parse each collection one at a time and assert the value of "name", "status" and "descriptions" at once for each child
Is that possible?
Yes, that's certainly possible.
Without knowing more about your actual data it's not possible to give a perfect example, but you could do something like:
jsonSlurper.results?.eachWithIndex { result, i ->
assert result.name == expectedNames[i]
assert result.status == expectedStatus[i] // or just "Healthy" if that's the only one
assert result.description == expectedDescriptions[i]
}
where expectedWhatever is a list of expected result fields. If your expected results really are based on index like in your example, then you could even calculate them within the loop, but I'm guessing that's not the case for real data.

Create an object that has a key where the value is an array

Basically, I want to somehow create a JSON object from a Groovy object. The Groovy object has key value pairs, and one of the values is a Groovy Array:
import groovy.json.*
// Imagine "handler" gets called somehow and an event gets passed to it.
def handler(event) {
def capabilitiesList = event.device.capabilities.findAll { attr -> attr.name != null }
def json = new JsonBuilder({
id event.deviceId
displayName event.displayName
value event.value
})
}
log.debug capabilitiesList
log.debug json.toPrettyString()
At this point, json.toPrettyString() gives me this:
{
"id": "asdfl469934623sdglsi3aqaq",
"displayName": "Some Lightbulb",
"value": "on"
}
And capabilitiesList gives me this:
["Test 1", "Test 2", "Test 3"]
How can I add the capabilitiesList array to the Groovy object so it gets converted to JSON?
I can't seem to get anything to work; the only thing that does work is this:
// ...
def json = new JsonBuilder({
id event.deviceId
displayName event.displayName
value event.value
capabilitiesList "Test 1", "Test 2", "Test 3"
})
// ...
Which gives me this (correct) JSON output:
{
"id": "asdfl469934623sdglsi3aqaq",
"displayName": "Some Lightbulb",
"value": "on",
"capabilitiesList": ["Test 1", "Test 2", "Test 3"]
}
But that obviously isn't useful because it's hard coded. So I tried referencing the Array directly like this:
// ...
def capabilitiesList = event.device.capabilities.findAll { attr -> attr.name != null }
def json = new JsonBuilder({
id event.deviceId
displayName event.displayName
value event.value
capabilitiesList capabilitiesList
})
// ...
But that breaks the JsonBuilder somehow, and it doesn't output anything.
I'm probably doing something really silly here but I can't quite figure out how to get this done. First time with Groovy as well. Thanks for the help!
Using the builder DSL should work. For example:
List list = ['Test1', 'Test2', 'Test3']
def builder = new groovy.json.JsonBuilder()
builder {
id "asdfl469934623sdglsi3aqaq"
displayName "Some Lightbulb"
value "on"
capabilitiesList list
}
println builder.toPrettyString()
prints
{
"id": "asdfl469934623sdglsi3aqaq",
"displayName": "Some Lightbulb",
"value": "on",
"capabilitiesList": [
"Test1",
"Test2",
"Test3"
]
}

Resources