Length is not worked in JSON Extractor in Jmeter - json

I need to get the count of card from json file. For this I've used $.storedCards.cards.lenght
in JSON Extractor but it doesn't work. There is an error message:
Options AS_PATH_LIST and ALWAYS_RETURN_LIST are not allowed when using path functions!
After that I've tried JSR223 PostProcessor with next script on goovy
def jsonText = '''${AllCards}''' //${AllCards} has json value
def json = new JsonSlurper().parseText(jsonText)
log.info( "Json length---------->"+json.resource.size())
${CardsCount} = props.get("4") //vars.put(json.resource.size.toString())
but there is problem with set value to my variable. Or when i've created variable in Groovy it was impossible to use outside from script.
My json file
"storedCards":
{
"cards":
[
{
"CardId":"123",
"cardBrand":"Visa",
"lastFourDigits":"2968",
},
{
"CardId":"321",
"cardBrand":"Visa",
"lastFourDigits":"2968",
},
..........
],
How can i get the count of card and set to my Variables? what should i use for this?

Your JSON data seems to be invalid. Assuming you have the valid JSON like below, I'm answering your question.
{
"storedCards": {
"cards": [
{
"CardId": "123",
"cardBrand": "Visa",
"lastFourDigits": "2968"
},
{
"CardId": "321",
"cardBrand": "Visa",
"lastFourDigits": "2968"
}
]
}
}
You dont need to write Groovy code, you can resolve this using JSON Extractor. Instead of using length function, use JSON path predicate like this-
$.storedCards.cards[*]
Though Variable you used in JSON Extractor won't give the solution right away, another JMeter function helps - __RandomFromMultipleVars
Excerpt from documentation -
The RandomFromMultipleVars function returns a random value based on the variable values provided by Source Variables.
The variables can be simple or multi-valued as they can be generated by the following extractors:
Boundary Extractor
Regular Expression Extractor
CSS Selector Extractor
JSON Extractor
XPath Extractor
XPath2 Extractor
Multi-value vars are the ones that are extracted when you set -1 for
Match Numbers. This leads to creation of match number variable called
varName_matchNr and for each value to the creation of variable
varName_n where n = 1, 2, 3 etc.
So once you use the predicate, you will get the count in the yourVariableName_matchNr. Example:-
Hope this help.

Related

Passing json string as an input to one of the parameters of a POST request body

I need to pass a json string as a value to one parameter of a POST request body. My request body looks like this:
"parameter1":"abc",
"parameter2":"def",
"parameter3": "{\"id\":\"\",\"key1\":\"test123\",\"prod1\":{\"id\":\"\",\"key3\":\"test123\",\"key4\":\"12334\",\"key5\":\"3\",\"key6\":\"234334\"},\"prod2\":{\"id\":\"\",\"key7\":\"test234\",\"key8\":1,\"key9\":true}}\"",
"parameter4":false,
"parameter5":"ghi"
}
For parameter3 I need to be pass a string value in json format. The json file is located in my local system and is a huge file, so it would make sense if I can pass it as a jmeter variable. I tried as below:
{
"parameter1":"abc",
"parameter2":"def",
"parameter3": "${jsonObj}",
"parameter4":false,
"parameter5":"ghi"
}
after adding a JSR223 preprocessor with the code below:
import org.apache.jmeter.util.JMeterUtils;
String fileContents = new File("path to json//myJson.json").getText('UTF-8');
vars.put("fileContents",fileContents);
var deltaJson = vars.get("fileContents");
var jsonObj = JSON.parse(deltaJson);
vars.put("jsonObj", JSON.stringify(jsonObj));
But I get below error:
exceptions":{"exceptionType":"System.JSONException","exceptionMessage":"Unexpected character ('$' (code 36)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at input location [1,2]"}
Can anyone help me in resolving this issue?
There is an easier way of doing this, JMeter comes with __FileToString() function so you can achieve the same much faster and without having to do any scripting
Something like:
{
"parameter1": "abc",
"parameter2": "def",
"parameter3": ${__FileToString(path to json//myJson.json,UTF-8,jsonObj)},
"parameter4": false,
"parameter5": "ghi"
}
Also be aware of the following facts:
the recommended language for using in JSR223 Test Elements is Groovy as it provides the maximum performance
you seem to be using JSON object which cannot be used outside of the browser context therefore your code fails to generate proper JSON hence your request fails as you're passing ${jsonObj} as it is, the substitution doesn't happen, you can look to jmeter.log file yourself and see the exact reason of your script failure

Jmeter JSON Extractor retrieve the second item from last of a list

I have a JSON response like below
{
"queryStartDate": "20170523134739822",
"queryEndDate": "20170623134739822",
"Rows": [
{
"hasScdHistoryOnly": false,
"Values": [
"1",
"53265",
"CO"
]
},
{
"hasScdHistoryOnly": false,
"Values": [
"1",
"137382",
"CO"
]
},
{
"hasScdHistoryOnly": false,
"Values": [
"1",
"310824",
"CO"
]
}
]
}
I am using Jmeter's JSON Extractor post-processor to receive the second value from the last of the 'Values' list. i.e. 53265, 137382, 310824.
I've tried to use $.Rows[*].Values[-2:-1], and $.Rows[*].Values[(#.length-2)], according to Stefan's introduction: http://goessner.net/articles/JsonPath/index.html#e2, but neither of them are working. Would you please help me out?
I believe JMeter is using JayWay JSON Path library, so you should be looking for the documentation here instead.
In general I would recommend using JSR223 PostProcessor as an alternative to JSON Path Extractors, both are applicable for basic scenarios only, when it comes to advanced queries and operators their behaviour is flaky.
Add JSR223 PostProcessor as a child of the request which returns above JSON
Make sure you have "groovy" selected in the "Language" drop down and "Cache compiled script if available" box is ticked
Put the following code into "Script" area
def values = com.jayway.jsonpath.JsonPath.parse(prev.getResponseDataAsString()).read('$..Values')
values.eachWithIndex { val, idx ->
vars.put('yourVar_' + (idx + 1), val.get(val.size()-2))
}
It should generate the following JMeter Variables:
yourVar_1=53265
yourVar_2=137382
yourVar_3=310824
which seem to be something you're looking for.
References:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
Using View Results tree's JSon Path Tester I could see that the following expression you used for extracting the values were not correct (correct for online JSONPath Online Evaluator but not working for JMeter)
Used Expression: $.Rows[*].Values[-2:-1]
Output from JSon Path Tester: No Match Found.
Used Expression: $.Rows[*].Values[(#.length-2)]
Output from JSon Path Tester: Exception: Could not parse token starting at position 16. Expected ?, ', 0-9, *
If the expression $.Rows[*].Values[1] is used it extracts the desired responses.
Used Expression: $.Rows[*].Values[1]
Output from JSon Path Tester:
Result[0]=53265
Result[1]=137382
Result[2]=310824

Jmeter json path extractor - How to Remove String

I have a problema with the next point:
{
"id":"3be62315-cd79-4e13-9536-0ee496e72184;1.0",
"objectType":"DOCUMENT",
"metadata":
{
"gdoc:filePath":null,
"gdoc:filename":"blankOdt.odt",
"gdoc:machineId":null
},
"checkedout":false,
"immutable":false,
"latestVersion":false,
"majorVersion":false,
"latestMajorVersion":false,
"contentStreamLength":0
}
I need recovery 3be62315-cd79-4e13-9536-0ee496e72184 and not "3be62315-cd79-4e13-9536-0ee496e72184;1.0",
I cant remove ";1.0" of the expression.
You can do it this way:
Suppose your JSON Path PostProcessor uses variable id for $..id
- Add a regex post processor after the JSON Post Processor and make it act on the variable
Then use ${id_part1}

How the JSON value extract process in jmeter response data using regular expression extractor

{
"response":{
"statusCode":"00",
"status":"success",
"responseData":
[
{
"status":1,
"themeID":27,
"themeName":"ThemeName25",
"templateId":22
}
},
{
"status":1,
"themeID":28,
"themeName":"ThemeName28",
"templateId":28
}
}
]
}
Here need to extract the json values from first and second array But without the use of jmeter plugins like JSON PATH EXTRACTOR. Can anyone suggest the idea for this?
Regular Expression Extractor is usually much faster compared to other extractors like XPath, JSON etc - Check this site for the comparison.
Lets assume we are trying to get the value of all the theme ids from the JSON.
Add a Regular Expression Extractor and update the details as shown here.
You need a reference name to store the value found
The pattern to check
Template used to create a string from the matches found
-1 for all matches, 0 for random, 1 for first ..etc
<variable>_matchNr will give the total matches
theme.id_1 will return the first match which is 27
theme.id_2 will return the second match which is 28
More details and examples are here.

Jmeter Xpath Extractor JSON

I'm trying to extract the parameter roomNo from the following JSON with JMETER XPATH Extractor:
*/
{
"categoryCode": ["I4"],
"Response": {
"class": "example",
"availables": {
"available": [
{
"Desc": " Middle",
"roomNo": "5049"
},
{
"Desc": " Middle",
"roomNo": "5062"
}
],
"class": "test"
},
"advisoryInfo": null
},
"storeId": "10251"
}
*/
i use the following expression with no success:
/Response/availables/available[0]/roomNo
is the expression wrong?
UPDATE:
i'm try to use the plugins JSON PATH EXTRATCTOR. i tryied the following queries with no success:
$...available[0]
$.Response.availables.available..roomNo[0]
$.Response.availables.available[0].roomNo
UPDATE1:
one more consideration: the ajax response I recieve starts with */, is it possible this creates troubles with JSON EXTRACTOR? i see the response through view Results Tree
UPDATE2:
i try the following approach:
ajax request followed by bash extractor, followed by json extractor but it is still not working
in bash extractor i did as suggested using the following strings
String temp = new String(prev.getResponseDataAsString());
prev.setResponseData(temp.replaceAll("\*/","").getBytes());
some more question:
is it possible to see the result of bash extractor?
should i declare before json extractor that it should use temp variable? how?
I'm afraid XPath Extractor won't let you parsing JSON.
You'll need JSONPath Extractor available via JMeter Plugins (you need Extras with Libs Set).
In your case relevant JSONPath query will look like:
$.Response.availables.available..roomNo[0]
Check out Using the XPath Extractor in JMeter guide (scroll down to Parsing JSON) for more information and XPath to JSONPath mappings table.
Hope this helps.
UPD. You can use Beanshell Post Processor to get rid of your */ bits, in that case JSONPath should work fine. Beanshell PostProcessor code:
String temp = new String(prev.getResponseDataAsString());
prev.setResponseData(temp.replaceAll("\\*/","").getBytes());
Make sure that Beanshell Post Processor goes before JSONPath Extractor.