The jsonPath object is used to apply JSON Path expressions to the payload, either for query, or for update. It is available only in the JSON filters.
There is a very nice online JSON Path evaluator available for experimenting with JSON paths and debugging expressions.
The jsonPath object has the following methods:
object read(string path) : returns the result of the provided path
object addToArray(string path, object valueToAdd) : add the provided value to the array(s) specified in the path
object put(string path, string key, object value) : sets the specified property's value in the object(s) indicated by the path.
object set(string path, object value) : sets the value of the property indicated by the path.
object delete(string path) : deletes the object(s) indicated by the path, if present.
In the following examples, we will assume that the payload is:
{
"store": {
"books": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95,
"onSale": false
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99,
"onSale": true
}
]
}
}
// Retrieve all the prices
let jsonPath = context.jsonHolder.jsonPath;
let prices = jsonPath.read("$.store.books[*].price");
// Returns: [8.95, 12.99]
// Retrieve the prices of books that are on sale
let jsonPath = context.jsonHolder.jsonPath;
let prices = jsonPath.read("$.store.books[?(@.onSale == true)].price");
// Returns: [12.99]
Set the "onSale" property of all books to true:
// Mark all books as on sale
let jsonPath = context.jsonHolder.jsonPath;
jsonPath.set("$.store.books[*].onSale", true);
Add a new property "rating" with a value of 10 to all books:
let jsonPath = context.jsonHolder.jsonPath;
jsonPath.put("$.store.books[*].rating", 10);
Delete all books which have category = "fiction"
let jsonPath = context.jsonHolder.jsonPath;
jsonPath.delete("$.store.books[?(@.category == 'fiction')]");