Looping over a JSON array from the Request
Using the {{#each <<some array>>}} {{/each}}
block in scripting allows you to loop over any array, including JSON arrays.
This is useful if we need to build a response based on all the items that might have been sent in a JSON array as part of the request payload.
You use {{#each}} in combination with the keyword this which is a pointer to the current object under the iterator.
Example: Using #each and this to render back items from a JSON array
Notice in this example we are passing the Request.Body 'JSONpath' '$.people'
function into the #each block. We enclose it in brackets as opposed to handlebars when doing this as it is being used as a parameter to the #each block which is already enclosed in handlebars.
Request Body | Templating script | Resulting Response Body |
{ "people": [ { "name": "John", "surname": "Doe", "age": 30 }, { "name": "Jane", "surname": "Lee", "age": 29 } ] }
| {{#each (Request.Body 'JSONpath' '$.people' ) }}
{{this.name}}
{{/each}} | John Jane |
Further to this we can use additional keywords to return the @index, the @key, and whether or not this is pointing at the last item in the array: @last.
Example: Generating a JSON response while looping over a JSON request
In this example we want to respond with a JSON array containing only the ages of the people passed in with the request.
We iterate over all the array items in the JSON request body, and populate our response based on the request items. We use this.age
to look into the person object under the iterator and extract the age. We use the last keyword to check that we are not at the end of the array in order to place a comma between the objects in the JSON array.
Request Body | Templating script | Resulting Response Body |
{ "people": [ { "name": "John", "surname": "Doe", "age": 30 }, { "name": "Jane", "surname": "Lee", "age": 29 } ] }
| { "ages": [ {{#each (Request.Body 'JSONpath' '$.people') }} {{this.age}} {{#unless @last}},{{/unless}} {{/each}} ] }
| { "ages": [ 30, 29 ] }
|
Last updated