SoapUi Assertions - Use a string as a json path with groovy - json

I am using groovy to automate some tests on SoapUI, and I wanted to also automate assertions in a way I would get a field's name and value from a *.txt file and check if the wanted field does exist with the wanted value in the SOapUI response.
Suppose I have the following json response:
{
"path" : {
"field" : "My Wanted Value"
}
}
And from my text file I would have the following two strings :
path="path.field"
value="My Wanted Value"
I tried the following :
import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def slurper = new JsonSlurper()
def json = slurper.parseText response
assert json.path==value;
But of course it doesn't work.
Any idea how can I get it done please?
Thank you

I think your problem is to access a json value from a path based with . notation, in your case path.field to solve this you can use the follow approach:
import groovy.json.JsonSlurper
def path='path.field'
def value='My Wanted Value'
def response = '''{
"path" : {
"field" : "My Wanted Value"
}
}'''
def json = new JsonSlurper().parseText response
// split the path an iterate over it step by step to
// find your value
path.split("\\.").each {
json = json[it]
}
assert json == value
println json // My Wanted Value
println value // My Wanted Value
Additionally I'm not sure if you're also asking how to read the values from a file, if it's also a requirement you can use ConfigSlurper to do so supposing you've a file called myProps.txt with your content:
path="path.field"
value="My Wanted Value"
You can access it using the follow approach:
import groovy.util.ConfigSlurper
def urlFile = new File('C:/temp/myProps.txt').toURI().toURL()
def config = new ConfigSlurper().parse(urlFile);
println config.path // path.field
println config.value // My Wanted Value
All together (json path + read config from file):
import groovy.json.JsonSlurper
import groovy.util.ConfigSlurper
def response = '''{
"path" : {
"field" : "My Wanted Value"
}
}'''
// get the properties from the config file
def urlFile = new File('C:/temp/myProps.txt').toURI().toURL()
def config = new ConfigSlurper().parse(urlFile);
def path=config.path
def value=config.value
def json = new JsonSlurper().parseText response
// split the path an iterate over it step by step
// to find your value
path.split("\\.").each {
json = json[it]
}
assert json == value
println json // My Wanted Value
println value // My Wanted Value
Hope this helps,

Related

facing difficulties in Json parsing in groovy

I have a json and its response is {"canMerge":false,"conflicted":true,"outcome":"CONFLICTED","vetoes":[{"summaryMessage":"Requires approvals","detailedMessage":"You need 2 more approvals before this pull request can be merged."}]}
and I want to filter out data on the basis of "outcome":"CONFLICTED" for this I have tried following ways-
def mergeResponse = readJSON file:mergeFileName
for(mergenew in mergeResponse.values)
{
if(mergenew.outcome == "CONFLICTED") {
echo "pull request can not merged"
}
when I am trying above it is skipping if loop directly eventhough condition match properly I am not getting why?
ALSO TRIED BELOW
import groovy.json.JsonSlurper
def slurper = new JsonSlurper().parseText(mergenew)
assert slurper.outcome == "CONFLICTED"
String id = mergenew.getString("id");
echo "pull request can not merged"
getting error for above is
hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parseFile() is applicable for argument types: (org.apache.commons.collections.map.ListOrderedMap$ListOrderedMapEntry) values: [canMerge=false]
Possible solutions: parse([B), parse([C), parse(java.io.File), parse(java.io.InputStream), parse(java.io.Reader), parse(java.net.URL)
I also approved script in jenkins script approval for JsonSlurper.parseText
Please help me. Any help is appreciated.
try this : (set the file name var to whatever the file is)
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
data = jsonSlurper.parse(new File(mergeFileName))
assert data.outcome == "CONFLICTED"
println("pull request can not merged")
You can use Pipeline Utility Steps to read a json file. This works for me:
def data = readJSON file: "${WORKSPACE}/data.json" // here just read the json file
def outcome = "${data.outcome}"
if(outcome == "CONFLICTED") {
echo "pull request can not merged"
}

Merge two JSONs from groovy

I have 2 JSON files and I want to merge those 2 and create one JSON message using groovy. Based on the "type" value I'm going to merge those two JSON files.
If the given "type" of JSON objects of JSON message 1 does not exist
in the JSON message2, the relevant JSON object should be contained in the output JSON message.
All the JSON objects from JSON message2 should be contained in the
output JSON message
Expected sample formats is shown below
Input JSON message1
{"message":[{"name":"HelloFile","type": "input"},{"name":"SecondFile","type": "error"}]
Input JSON message2
[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]
Expected JSON
{"message":[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"},{"name":"SecondFile","type": "error"}]}
I used the below groovy code.
JsonBuilder jsonBuilder = new JsonBuilder(JSON1)
jsonBuilder.content.message= JSON2
def updatedBody = jsonBuilder.toString()
From the above code, I got the below message.
{"message":[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]}
Any help sorting this would be much appreciated.
Try using JsonSlurper:
import groovy.json.*
​def json1 = '{"message":[{"name":"HelloFile","type": "input"},{"name":"SecondFile","type": "error"}]}'​​​​​​​​​​​​​
def json2 = '[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]'
def slurper = new JsonSlurper()
def json1Obj = slurper.parseText(json1)
def json2Obj = slurper.parseText(json2)
json1Obj.message+=json2Obj
println JsonOutput.toJson​(json1Obj)​
This prints:
{"message":[{"name":"HelloFile","type":"input"},{"name":"SecondFile","type":"error"},{"name":"NewFile","type":"input"},{"name":"MyFile","type":"output"}]}

Groovy: Correct invalid JSON as per XML specifications

I am trying to correct the Incoming JSON as I have a JSON to XML converter. I wish to replace the leading number in a field etc 1Doc1 to S_Doc1 etc. Also I Need to replace the invalid XML element names from JSON such as Slash etc. Here is my Code but it is not working:
def list = new JsonSlurper().parseText( payload )
list.each {
def oldStr = "" + it
def newStr = oldStr.replaceFirst("^[^a-zA-Z]+", "S_")
payload = payload.replaceFirst(oldStr, newStr)
}
return payload
I get the Input as is. Could anyone advise how to do this in Groovy. For example if my Input is:
{
"1Document1":
{"Record":{"Header"...….
The Output should be
{
"S_Document1":
{"Record":{"Header"......
You can use eachWithIndex and update the element in the list using key instead of trying to manipulate the input string:
import groovy.json.JsonSlurper
String json = '[{"1Document1": {"Record":{"Header": "xx"}}}, {"2Document1": {"Record":{"Header": "zz"}}}]'
def list = new JsonSlurper().parseText( json )
list.eachWithIndex {v, k ->
def newStr = (""+v).replaceFirst("^[^a-zA-Z]+", "S_")
list[k] = newStr
}
println list

Groovy script json response length

I need to find json response length. Sample response looks like below:
{
"resource": {
"name":"aaaaaaaaaaa",
"emailid":"bbbbbbbbb"
}
}
As two parameters are present in resource. So, i should have got response as 2.
Please let me know hoe i can find json length as 2
This is the working solution, try this
import groovy.json.JsonSlurper // import this class
def jsonText = '''{
"resource": {
"name":"aaaaaaaaaaa",
"emailid":"bbbbbbbbb"
}
}'''
def json = new JsonSlurper().parseText(jsonText)
println "Json length---------->"+json.resource.size()
If you have the JSON object, you don't need to parse JSON string to json, yo can directly do the following,
println jsonObject.resource.size() // Here resource is the key(sub node) inside your json
If you want to get the length of parent JSON key, just do as follows,
println jsonObject.size()
Based on your question, it appears that you would like to know the count of properties within a JSON object. So we can do that by following these steps:
STEP 1 : Parse the response string into JSON object
STEP 2 : Convert JSON object into groovy Map object
Step 3 : Call size() method on Map object to get the elements count within the map object
So your code would like this :
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def response = jsonSlurper.parseText('{ "resource": {"name":"aaaaaaaaaaa","emailid":"bbbbbbbbb"}}')
def object = (Map)response.resource
log.info object.size()
So your output will be 2. You can try adding more elements to JSON object check if it works.
Hope this helps :)

reading name of json using groovy

I have the below JSON structure and I am trying to retrieve the name order/sale/Cancel to a string variable in groovy
{"Transaction" : {"Order" : { ......
{"Transaction" : {"Sale" : { ......
{"Transaction" : {"Cancel" : { ......
I was able to get to this point, reading the JSON using JSON slurper with some research but not sure how to get read the name.. most of the articles I have seen the point to reading the values and not the name.
final BufferedReader inReader = new BufferedReader(new InputStreamReader(inputStream, 'UTF-8'))
Object result = jsonSlurper.parse(inReader)
I have converted from XML to JSON so if this can be done using either XML or JSON would help.
Correct would be to use :
def json = '{"Transaction" : {"Order" : "result"} }'
def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText(json)
assert 'Order' == result.Transaction.keySet().first()
If you have JSON in String you don't need to create BufferedReader, just use parseText. After you parse JSON you can just access it by traversing properties.
def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText(inputStream.text)​;
result.Transaction.Order​ //result