I have created a json block file which looks like this, I like to add a new element i.e
{
"Id": 0,
"cc": "123"
}
I need to add a new element
"xyz": ${abc}
the resulting to look like
{
"Id": 0,
"cc": "123",
"xyz": ${abc}
}
I have retrieved the file
String json1 = vars.get("basePath")+"Jmeter/Results/json1";
json1= new groovy.json.JsonSlurper().parse(json1);
How do I add
"xyz": ${abc},
to json1 ?
Use the following code:
String json1 = vars.get("basePath")+"Jmeter/Results/json1";
def parsedJson = new groovy.json.JsonSlurper().parse(json1);
parsedJson.put('xyz',vars.get('abc'))
def newJson = new groovy.json.JsonBuilder(parsedJson).toPrettyString()
More information:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
Related
I would like to remove the array SEO from the json when the keys "Description" and "Title" in the has no value.
json:
[
{
"SEO": [
{
"Description": "",
"Title": ""
}
],
"accesoires": [
"1167296"
],
"shortCode": "S-576",
"spareParts": [
"800236"
]
}]
I tried the below code but i'm not able to remove the array.
def Message processData(Message message) {
def body = message.getBody(String);
def json = new JsonSlurper().parseText(body)
json.each{
it.SEO.each{
if(!(it.findResults{k, v -> v?.size() > 0 && v[0]?.length() > 0 ? v[0] : null })){
json.remove("SEO")
} } }
def out= JsonOutput.toJson(json)
message.setBody(out)
return message}
To remove the array "SEO" from the JSON when the keys "Description" and "Title" have no value, you can use the following Groovy code:
def jsonString = '[{"SEO": [{"Description": "", "Title": ""}], "accesoires": ["1167296"], "shortCode": "S-576", "spareParts": ["800236"]}]'
def json = new JsonSlurper().parseText(jsonString)
for (item in json) {
if (!item.SEO[0].Description && !item.SEO[0].Title) {
item.remove('SEO')
}
}
println(JsonOutput.toJson(json))
This will first parse the JSON string into a list of maps using JsonSlurper. Then it iterates through each map in the list and checks if the "Description" and "Title" keys in the "SEO" array are empty. If they are, it removes the "SEO" array from the map using the remove() method. Finally, it prints the modified JSON using the JsonOutput.toJson() method.
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);
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"}"}
In Jmeter JSR223Preprocessor with Groovy I load a generic JSON file xyz looking like this:
{
"name": "dummy",
"block1": {
"var1": 1,
"var2": {
"value": 1,
"unit": "Miles",
},
"var3": {
"value": 3,
"unit": "Seconds",
},
"myList": [{"Id": 0}]
}
I like to come up with an elegant way to replace the var2 "Value" with a configurable value sayconfVal. This works:
String path = vars.get("basePath")+"xyz.json" ;
xyz = new File(path).getText("UTF-8");
xyz = xyz.replaceAll ('"value": 1', '"value": ${confVal}');
However I am not comfortable with this because it is vulnerable with spaces, and moreover I have another Value on var3 and someone could accidentally change 1 to 3. So I like to index to that child var2.Value then get Value.
Thank you
Add JSR223 PreProcessor as a child of the HTTP Request which body you need to amend
Put the following code into "Script" area:
def xyz = new File(vars.get("basePath")+"xyz.json")
def request = new groovy.json.JsonSlurper().parse(xyz)
request.block1.var2.value=vars.get('confVal') as int
xyz.newWriter().withWriter { writer ->
writer << new groovy.json.JsonBuilder(request).toPrettyString()
}
That's it, the value in the file should be replaced with what you have in the ${confVal} variable in the runtime.
More information:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
I have the following JSON response in SoapUI
{
"formatted": {
"line1": "14/8 QUAY STREET",
"line2": "14/8 QUAY STREET"
},
"structure": {
"level": null
},
"location": {
"nzX": 1758749.75300025
},
"references": {
"aid": "A1003467096"
}
}
I want the following as the output
formatted, structure, location and references.
I am using Json slurper but i am not able to get all the parent element names.
How do i do it using JSON slurper in groovy.
Assuming the JSON is in a string s, consider the following which illustrates getting the top level keys:
import groovy.json.*
def json = new JsonSlurper().parseText(s)
def parentNames = json.keySet()
parentNames.each { println it }