I am parsing a JSON string with Groovy's JsonSlurper. I want to find out how to (1) check if a field is missing from the string OR (2) if its value is set to null. This is my code:
def JsonSlurper jSlurp = new JsonSlurper()
def obj = jSlurp.parseText(myJsonString)
assert obj.myField == null
Unfortunately, this does not tell me if the field is missing or if its present with a value of null. How do I figure that out?
def obj = new groovy.json.JsonSlurper().parseText('{"a":null, "b":1}')
assert obj.containsKey('a')==true
assert obj.a==null
assert obj.containsKey('c')==false
assert obj.c==null
Related
I got a string from a server response:
responseString:"{"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1"}"
then I do:
responseString[1..-2].tokenize(',')
got:
[""session":"vvSbMInXHRJuZQ=="", ""age":7200", ""prid":"901Vjmx9qenYKw"", ""userid":"user_1""]
get(3) got:
""userid":"user_1""
what I need is the user_1, is there anyway I can actually get it? I have been stuck here, other json methods get similar result, how to remove the outside ""?
Thanks.
If you pull out the proper JSON from responseStr, then you can use JsonSlurper, as shown below:
def s = 'responseString:"{"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1"}"'
def matcher = (s =~ /responseString:"(.*)"/)
assert matcher.matches()
def responseStr = matcher[0][1]
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def json = jsonSlurper.parseText(responseStr)
assert "user_1" == json.userid
This code can help you get you to the userid.
def str= 'responseString:"{:"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1","hdkshfsd":"sdfsdfsdf"}'
def match = (str=~ /"userid":"(.*?)"/)
log.info match[0][1]
this pattern can help you getting any of the values you want from the string. Try replacing userid with age, you will get that
def match = (str=~ /"age":"(.*?)"/)
#Michael code is also correct. Its just that you have clarified that you want the user Name to be specific
I am trying to retrieve a list of all instances of 'search' from a json response and set it so that any values that contains 'null' is changed to 0. However I am getting an error stating no such property: it for class. How can I fix this to ensure I get the code working so any instance of 'null' changes to 0?
import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def json = new JsonSlurper().parseText(response)
def resultItems = json.xxx.xxx.items
def resultSearchCostGroup = json.xxx.xxx.xxx.search
int totalSearchCostGroup = resultSearchCostGroup.flatten().collect(it ?:0 ).sum()
Your last line should read
int totalSearchCostGroup = resultSearchCostGroup.flatten().collect { it ?:0 }.sum()
I am having a little issue with my if condition in groovy.
Virtually I want to look at a property value I've set and ensure that is every instance on the response delivered from the JSON contains the same value as the property value, then it should equal a match. Now when I log the location_id and location_id_request, I am getting the values expected. However, in my if statement it seems to still state that that the location id does not match, making me believe that my if condition is incorrect. What do I need to change my if condition to, to output the correct message.
Below is the code I have with the log information underneath:
import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def json = new JsonSlurper().parseText(response)
def location_id = json.reviews.location_id
assert location_id != null
def location_id_request = messageExchange.modelItem.testStep.testCase.getPropertyValue("locationid")
assert location_id.every {it == location_id_request}
log.info location_id_request
log.info location_id
if (location_id == location_id_request)
log.info "Good News, location match!"
else
log.info "Test has failed, location do not match!"
Log information in correct order:
location_id_request:INFO:000000
location_id:INFO:[000000, 000000, 000000, 000000, 000000]
if condition output:INFO:Test has failed, location do not match!
You compare a String (Number?) with List - it won't work. Instead, try to check if given location_id is present on location_id_request List:
if (location_id in location_id_request) { //... }
I am writing a script assertion to see if a element value contains in the array list and if it does, it passes.
When I print the element:Number, I get like an example [1,2,3,3] as array. If Number contains say 3, script has to pass.
I have written below code which is failing, probably because the written value is an array list, how to assert an array value?
def response = messageExchange.getResponseContent()
def xml = new XmlSlurper().parseText(response)
def invoiceNumber= xml.'**'.findAll { it.name() == 'Number'}
log.info "$invoiceNumber"
assert invoiceNumber.contains(1)
The problem is that invoiceNumber is a Collection of groovy.util.slurpersupport.NodeChild elements instead of Integer elements. This is why the contains(3) comparison never returns true.
You've to convert array of groovy.util.slurpersupport.NodeChild to array of integers before the contains(), you can do it using the spread dot operator an NodeChild.toInteger(), so your script must be:
def response = messageExchange.getResponseContent()
def xml = new XmlSlurper().parseText(response)
def invoiceNumber= xml.'**'.findAll { it.name() == 'Number'}
log.info "$invoiceNumber"
// convert the array to array of integers
invoiceNumber = invoiceNumber*.toInteger()
// now you can perform the assert correctly
assert invoiceNumber .contains(3)
Hope it helps,
I'm trying to parse XML from my Request in Soapui. And when I parse a Node without anything in it, logically the String is Null if the defining func() returns Null:
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def request = groovyUtils.getXmlHolder( mockRequest.requestContent )
def argumentString = request.getNodeValue("/soap:Envelope/soap:Body[1]/emm:RunApplication[1]/emm:argument[1]")
now I tried doing it like this:
try{argumentString.length()}catch(e){argumentsString = " "}
but this kills the Process after the correction, and doesn't quite give what I want. Can't use a Simple if(func()!=NULL) as i'm used to in Java? How can I do this? Thanks for your Help!
You can test for null values ...:
argumentString = (argumentString != null) ? argumentString : " "
BTW, with argumentString?.length(), length() will only be evaluated if argumentString isn't null.