How to Handle JSON in Tests

Prev Next

Catchpoint treats JSON (JavaScript Object Notation) as flat text. In order to use Transaction and API tests to extract data from JSON and verify the values, use the following macros and commands: ${Extract}, ${Switch}, ${Var}, and Assert().

${Extract} is used to store a desired value from the request URL, request headers, response headers, or the response itself. The following example uses ${Extract} to fetch the value of "url". After storing the value in a variable, the ${Switch} and ${Var} macros are used to verify the value of "url" is set as expected. Based on the extracted value, the switch macro will return true or false, which is stored in a boolean variable. Lastly, Assert() is used to fail the transaction if the response is false. If the response is true, the expected value is successfully verified.

Example

// open the URL to get the JSON
open("http://httpbin.org/get")

//extract value from response to match key (url) we are looking for using regex
var test = ${Extract('resp-content','regexp:"url":.*"(.*)".*')}

//bool is true if 'test' equals to "http://httpbin.org/get", otherwise false
var bool = ${Switch("${var(test)}","http://httpbin.org/get","true","false")}

//assert to test if we got true (test will fail if false)
assert(${var(bool)})

Example of a successful test:

scripting_suc.png

Example of a failed test

kb_failed.png

JSONPath Parsing

Catchpoint supports JSONPath parsing in addition to Regular Expressions in API tests. JSONPath is very similar to XPath, enabling you to address and extract data from within the file. Below is a chart that compares the syntax for the two paths for writing JSONPath expressions.

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

Example:

storeVariable("${Extract(resp-content, json:$..book[?(@.isbn)])}", "book")

This extracts all array(s) from the response content with the ISBN number in it and stores it as the variable book.