The jsonPath object

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.

Methods

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.

Examples

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

}

]

}

}


Querying the payload

// Retrieve all the prices

let jsonPath = context.jsonHolder.jsonPath;

let prices = jsonPath.read("$.store.books[*].price");

// Returns: [8.95, 12.99]


More advanced query of the payload

// 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]


Modifying the payload using a JSON path

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);


Adding a new object to the payload

Add a new property "rating" with a value of 10 to all books:

let jsonPath = context.jsonHolder.jsonPath;

jsonPath.put("$.store.books[*].rating", 10);


Removing objects from the payload

Delete all books which have category = "fiction"

let jsonPath = context.jsonHolder.jsonPath;

jsonPath.delete("$.store.books[?(@.category == 'fiction')]");