Response Templating - Working with JSON

MockLab provides the jsonPath 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

  "outer": {
    "inner": "Stuff"

The following will render “Stuff” into the output:

{{jsonPath request.body '$.outer.inner'}}

And for the same JSON the following will render { "inner": "Stuff" }:

{{jsonPath request.body '$.outer'}}

Iterating over JSON elements

The jsonPath 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:

  "things": [
      "id": 1
      "id": 2
      "id": 3

And the following response body template:

{{#each (jsonPath request.body '$.things') as |thing|}}
thing: {{{}}}{{/each}}

The response body will contain:

thing: 1
thing: 2
thing: 3

The above will only work if the JSONPath expression selects an array from the request JSON. However, each can also be used to iterate over maps/objects, so given the request JSON:

  "things": {
    "one": 1,
    "two": 2,
    "three": 3

And the template:

{{#each (jsonPath request.body '$.things') as |value key|}}

The output would contain: