Jmeter json path extractor - How to Remove String - json

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}

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

Length is not worked in JSON Extractor in Jmeter

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.

How to extract values from json in jmeter when the keys are unkown?

I have a json response as,
{
'sadasd123242' : 'asdadada122dfsfs',
'dadsadaskljk' : 'adasdasdasdsadds'
}
I want to extract the keys from the response in jmeter test using the JSON extractor. I am unable to do this as I do not know the keys in the response. How do I get the keys ?
Assuming you have the response in the following format:
{
"data": {
"assets": {
"sadsad12dwqqwe": "asda1212312",
"asdasd1213123": "asdas2131231"
}
}
}
You can extract key names using JSR223 PostProcessor and the following code:
new groovy.json.JsonSlurper().parse(prev.getResponseData()).data.assets.eachWithIndex{ def node, int idx ->
log.info('Key ' + idx + '=' + node.getKey())
vars.put('key_' + idx, node.getKey())
}
It will print key names into jmeter.log file and create JMeter Variables like:
- `${key_1}`
- `${key_2}`
- etc.
holding the required "key" values.
Demo:
References:
Apache Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
Considering first value as key which is dynamic and second value you have to fetch.
You can use "Boundary extractor" post processor in that case by defining the left and right boundary as shown in the below image.
Check the below test for boundary expression to get the desired result:-
Hope this help.

In Jmeter, Unable to extract only the first key from a JSON response

I want to extract the first key from the json response, which should be passed as an input for next HTTP request in Jmeter.
This is my input (javascript object):
Object({"details": { "key1": {"s_1": "s_v", "s_2": "s_v" }, "key2": {"s_1": "s_v", "s_2": "s_v" } }})
I need to get "key1" in a variable.
Try "JSON Path PostProcessor" in Post Processors and the expression may be "$..key1".
Add Regular Expression Extractor as a child of the request which returns the above response.
Configure the Regular Expression Extractor as follows:
Reference Name: anything meaningful, i.e. key_1
Regular Expression: "key1": {(.+?)}
Template: $1$
Refer the extracted value as ${key_1} where required
You can test your Regular Expressions using "RegeExp Tester" mode of the View Results Tree listener
Demo:
References:
Regular Expressions
Using RegEx (Regular Expression Extractor) With JMeter
Perl5 Regex Cheat Sheet

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.