If your web services are RESTful, you will get JSON responses. In Apache JMeter, there is a JSON Extractor (i.e., a Post Processor) available for parsing JSON responses.
In this article, we will introduce JSONPath, which is used in JSON Extractor, and present an example of selecting an object/element based on multiple criteria with it.[1]
JSON Extractor / JSONPath
JSONPath is the XPath for JSON. Since a JSON structure is normally anonymous, JSONPath assigns symbol $ as the root object.
Below is a side-by-side comparison of the JSONPath syntax elements with its XPath counterparts.[3]
XPath
|
JSONPath
|
Description
|
/
|
$
|
the root object/element
|
.
|
@
|
the current object/element
|
/
|
. or []
|
child operator
|
..
|
n/a
|
parent operator
|
//
|
..
|
recursive descent. JSONPath borrows this syntax from E4X.
|
*
|
*
|
wildcard. All objects/elements regardless their names.
|
@
|
n/a
|
attribute access. JSON structures don't have attributes.
|
[]
|
[]
|
subscript operator. XPath uses it to iterate over element collections and for predicates. In Javascript and JSON it is the native array operator.
|
|
|
[,]
|
Union operator in XPath results in a combination of node sets. JSONPath allows alternate names or array indices as a set.
|
n/a
|
[start:end:step]
|
array slice operator borrowed from ES4.
|
[]
|
?()
|
applies a filter (script) expression.
|
n/a
|
()
|
script expression, using the underlying script engine.
|
()
|
n/a
|
grouping in Xpath
|
JSONPath expressions can use the dot–notation
$.ccapiInfo.canonicalLink
or the bracket–notation
$['ccapiInfo']['canonicalLink']
for input paths. For the internal or output paths, they will always be converted to the more general bracket–notation.
Selecting on Multiple Criteria with JSONPath
Given an array of books, the following JSONPath applies two filters (e.g., "price" and "category") on the array to retrieve the name of author matching the criteria:
JSON Input
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
JSONPath Syntax
$..book[?(@.price==8.99 && @.category=='fiction')] .author
Below shows the evaluation result using JSONPath Online Evaluator with the above input and JSONPath Expression:
Evaluation Results
[
"Herman Melville"
]
More Examples
Given the same input, you can also retrieve different objects (or elements) using the following JSONPath expressions:[4]
1 comment:
how to get the list of categories.
For example book and bicycle?
Post a Comment