Jmeter Xpath Extractor JSON - 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.

Related

What is the ideal way to JSON.stringify in Terraform?

I'm working on my first Terraform project and I'm looking for the best way to stringify a JSON object. The resource I'm defining has a parameter that expects a JSON string. JSON structure is:
"document": {
"tag": "String Title",
"response": "There's a string response and perhaps a price like $[XX.XX]."
}
}
I don't think jsonencode or jsondecode do this. I could stringify them in advance but that isn't scalable in this case. I wasn't sure if I could do this with JavaScript or another language alongside Terraform, or if there's a function in HCL that will do it.
jsonencode in Terraform is exactly equivalent to JSON.stringify with only one argument in JavaScript.
For example, if you need to assign a string containing a JSON object to an argument called something_json, you could do that like this:
something_json = jsonencode({
document = {
tag = "String Title"
response = "There's a string response and perhaps a price like $[XX.XX]."
}
})
The above would set something_json to a minified version of the following JSON:
{
"document": {
"tag": "String Title",
"response": "There's a string response and perhaps a price like $[XX.XX]."
}
}
Terraform does not have an equivalent of the optional replacer and space arguments in JavaScript's JSON.stringify:
An equivalent of replacer isn't needed in Terraform because all possible values in the Terraform language have a defined JSON equivalent as described in the table in the jsonencode documentation.
space is for generating non-minified JSON; Terraform does not offer any way to do this because it is focused on generating JSON for machine consumption and so prefers to generate the most compact representation possible.

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.

JSON Path PostProcessor: storing JSON arrays and objects loses their data type

I'm using JSON Path PostProcessor with path expressions to store a JSON object from a JSON response, but when I later retrieve the variable, it has been reduced to string with key - pair values. So I don't know that was a string or number.
Example:
Response looks like this
{
.
.
"currency" : {
"code" : "AUD",
"name" : "Australian Dollars",
"symbol" : "$"
},
.
}
Using the path expression, I find currency and save it.
However, when I use it in a HTTP Request body data ("currency" : ${currency},),
it comes like this:
"currency" : {code=AUD, name=Australian Dollars, symbol=$},
How do I get the JSON Path PostProcessor to save the JSON object 'as is" without losing the data type details? Should I be using a different approach instead of JSON Path?
I would recommend switching to JSR223 PostProcessor and Groovy language, this way you will have full control of what is going on and be able to do what you want.
Assuming you have the following JSON response:
{
"currency": {
"code": "AUD",
"name": "Australian Dollars",
"symbol": "$"
}
}
the relevant Groovy coode will be something like:
def json = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def currency = json.currency
def currencyString = new groovy.json.JsonBuilder(currency).toPrettyString()
vars.put('currency', currencyString)
log.info(currencyString)
Demo:
References:
Groovy - Learn
Groovy - Parsing and producing JSON
Groovy is the New Black

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}