Extracting data with JSONPath
WireMock Cloud provides thejsonPath
helper which will extract values from a JSON document
using the JSONPath expression language.
Similar in concept to XPath, JSONPath permits selection of individual values or sub-documents
via a query expression.
For example, given the JSON
{ "inner": "Stuff" }
:
Iterating over JSON elements
ThejsonPath
helper outputs a “one or many” collection, which can either
be printed directly, or passed to further helpers such as each
or join
.
For instance, given a request body of the form:
each
can also be used to iterate over maps/objects, so given
the request JSON:
Adding to a JSON Array
ThejsonArrayAdd
helper allows you to append an element to an existing json array.
Its simplest form just takes two parameters, the array to append to and the item to be added:
maxItems
parameter:
maxItems
parameter:
flatten
attribute:
jsonArrayAdd
helper to add items to a nested array. This is achieved using the jsonPath
property
and referencing the array you want to add an item to:
Removing from a JSON Array or Object
ThejsonRemove
helper allows you to remove an element from an existing json array, or remove a key from an existing
json object, by identifying it using a json path expression.
For instance, given an existing array like this:
123
:
name
:
Merging JSON objects
ThejsonMerge
helper allows you to merge two json objects. Merging will recurse into any common keys where the values
are both objects, but not into any array values, where the value in the second object will overwrite that in the first.
Given these two objects:
jsonArrayAdd
helper, the second object can be provided as a block:
Removing attributes
ThejsonMerge
helper has an optional removeNulls
parameter which, when set to true will remove any attributes from the resulting JSON that
have null values in the second JSON document.
So for instance, given the following template:
Formatting JSON
TheformatJson
helper allows you to output JSON in either a pretty or a compact format. The default is pretty:
Reading object as JSON
TheparseJson
helper will take the string value of the provided variable (or the contents of the block) and parse it
into an object or array, and assign it to the given variable.
e.g.
newVariableName
that can be used in subsequent helpers.
The contents to parse can also be supplied inline:
Writing data as a JSON string
ThetoJson
helper will convert any object into a JSON string.