no such property: it for class - groovy

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

Related

Groovy JsonSlurper - How to check for null value vs missing field?

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

how can I get value from json object in 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].

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

obtain value from Key/value in map array groovy

I have code like this:
def options = JsonPath.read(prev.getResponseDataAsString(), '$.options')
def randomOption = options.get(RandomUtils.nextInt(0, options.size()))
def code = randomOption.get("code")
vars.put('code1', code)
def values = randomOption.get('values')
def randomValue = values.get(RandomUtils.nextInt(0, values.size())) as
String
def val = randomValue['value']
vars.put('randomValue', randomValue)
vars.put('ValueF', val).
In Random Variable i am getting value as [label:Red, value:8] . I need to fetch the value of Value=8
Youre trying to invoke
vars.put('ValueF', [label:Red, value:8])
which is put(String, Map)
JMeterVariables have no such method https://jmeter.apache.org/api/org/apache/jmeter/threads/JMeterVariables.html
you can use putObject() which accepts String as key and Object as value:
vars.putObject('ValueF', val)

No such property: expected for class: Script1343 (in groovy script);

I am trying to retrieve data from oracle db but getting No such property: expected for class: Script1343 (in groovy script); error
import java.util.Properties;
import java.io.InputStream;
import groovy.sql.Sql;
def url = 'jdbc:oracle:thin:#//localhost:1521/TEST'
def user = 'DB'
def password = 'DB'
def driver = 'oracle.jdbc.driver.OracleDriver'
def sql = Sql.newInstance('url', 'User', 'password','oracle.jdbc.driver.OracleDriver')
sql.withStatement {
stmt -> stmt.queryTimeout = 30
print "Request TimeOut"
}
def rowNum = 0
sql.eachRow("SELECT DISTINCT CST_START_DT_PF,CST_ITEM_NUM_PF FROM COST "){ row ->
def first = row[0]
def middle = row.CST_START_DT_PF
def one = row.CST_ITEM_NUM_PF
assert expected[rowNum] == "$CST_START_DT_PF, $CST_ITEM_NUM_PF"
}
There are several things wrong. The specific error you asked about is the result of the following:
assert expected[rowNum] == "$CST_START_DT_PF, $CST_ITEM_NUM_PF"
You are referencing a variable expected which doesn't exist.
You didn't ask about the things below but other problems you are going to run into...
Referencing $CST_START_DT_PF and $CST_ITEM_NUM_PF is going to be a problem because they also don't exist, at least not in a way that your code will work.
You also are probably going to get unexpected results related to the fact that you are never incrementing rowNum.

Resources