how can I get value from json object in groovy - groovy

def RawRecordsDateRangeResponse = context.expand('${getRawRecordsForDateRange#Response}')
log.info RawRecordsDateRangeResponse
My response is:
{"2018-09-03":"https://dhap-dconnect-telemetry-data-dev2.s3.amazonaws.com/ULT/d83350d2-af56-11e8-b612-0242ac11001118/temperature/raw-2018-09-03.json"}
Here I want to get the value from the json response key as date.

Your response represents JSON document and it stores it in variable of type String. You can parse it using groovy.json.JsonSlurper class. Consider following example:
import groovy.json.JsonSlurper
def RawRecordsDateRangeResponse = context.expand('${getRawRecordsForDateRange#Response}')
def json = new JsonSlurper().parseText(RawRecordsDateRangeResponse)
def url = json.'2018-09-03'
println url
Output:
https://dhap-dconnect-telemetry-data-dev2.s3.amazonaws.com/ULT/d83350d2-af56-11e8-b612-0242ac11001118/temperature/raw-2018-09-03.json

If it's just the key of the JSON message you need rather than the value, you could use something like:
import groovy.json.JsonSlurper
def rawRecordsDateRangeResponse = '''{"2018-09-03":"https://dhap-dconnect-telemetry-data-dev2.s3.amazonaws.com/ULT/d83350d2-af56-11e8-b612-0242ac11001118/temperature/raw-2018-09-03.json"}'''
def json = new JsonSlurper().parseText(rawRecordsDateRangeResponse)
def date = json.collect({it.key})
print date
This produces [2018-09-03].

Related

Cannot get property after using jsonSplurper.parseText(prev.getResponseDataAsString())

I'm a new on Jmeter, I'm using JSR223 PostProcessor to get some properties in the response. Unfortunately, my response is returned as a string json as below:
"{\n "trueOdds": "1.9047619047619047",\n "displayOdds": "1.90",\n "minStake": 50.0,\n "maxStake": 105263,\n "selectionId": "11318855000001015h",\n "oddsStyle": "de",\n "offerId": "1911208285033005"\n}"
Now I want to get trueOdds, displayOdds for using in the next request. I tried to use following code to get them:
import groovy.json.JsonSlurper
def jsonString = prev.getResponseDataAsString();
def jsonSlurper = new JsonSlurper();
def object = jsonSlurper.parseText(jsonString);
vars.put("trueOdds", object.trueOdds);
vars.put("displayOdds", object.displayOdds);
But I get following error:
ERROR o.a.j.e.JSR223PostProcessor: Problem in JSR223 script, JSR223
PostProcessor javax.script.ScriptException:
groovy.lang.MissingPropertyException: No such property: trueOdds for
class: java.lang.String
Can anyone support to resolve this? thanks a lot.
I cannot reproduce your issue given the following JSON payload:
{
"trueOdds": "1.9047619047619047",
"displayOdds": "1.90",
"minStake": 50.0,
"maxStake": 105263,
"selectionId": "11318855000001015h",
"oddsStyle": "de",
"offerId": "1911208285033005"
}
Demo:
If your response looks exactly how you show it to us it's not a valid JSON therefore you need:
Remove first and last " via i.e. substring function
Remove all occurrences of \n via i.e. replaceAll function
Suggested code amendment:
import groovy.json.JsonSlurper
def jsonString = prev.getResponseDataAsString();
def withoutQuotationMarks = jsonString.substring(1, jsonString.length() - 1)
def withoutLineBreaks = withoutQuotationMarks.replaceAll('\\\\n','')
def jsonSlurper = new JsonSlurper();
def object = jsonSlurper.parseText(withoutLineBreaks);
vars.put("trueOdds", object.trueOdds);
vars.put("displayOdds", object.displayOdds);
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It

Need to remove unwanted symbols from value using replaceAll method

I am getting the value of a field as ["value"]
I want to print only the value removing the [ "from the result value.
That looks like a JSON array of Strings? No idea, as you don't provide any context, but you could do:
import groovy.json.JsonSlurper
def valueField = '["value"]'
def result = new JsonSlurper().parseText(valueField).head()
println result
Prints value
The following script should be what you need
def str = '["value"]'
println(str.replaceAll(/\[|\]/,''))

SoapUI to get attachment from response in Groovy

I tried to use following code to get attachment from reponse as text in Groovy.
def testStep = testRunner.testCase.getTestStepByName("getData")
def response = testStep.testRequest.response
def ins = response.attachments[0].inputStream
log.info(ins);
It contains some binary information too, so it is not fully human readable, but got following in output:
java.io.ByteArrayInputStream#5eca74
It is easy to simply encode it to base64 and store it as a property value.
def ins = response.attachments[0].inputStream
String encoded = ins.bytes.encodeBase64().toString()

groovy extract value from string

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

no such property: it for class

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()

Resources