foreach
The foreach
statement defines a block of zero or more statements and associates this block with multiple values. The block of statements is executed repeatedly, once for each value.
Syntax
foreach
parslet
as
loop_label
{
}
The opening {
may be placed on a line of its own if preferred
Details
The foreach
statement is used to iterate over the values in an array or object (identified by a parslet) within the data in a named buffer.
The loop will execute for as many elements as there are in the array, or for as many members there are in the object. For the purposes of this documentation, the term child will be used to refer to a single array element or object member.
If the array or object is empty, then the body of the loop will be skipped and execution will continue at the statement following the closing }
.
The loop_label can be any string, but must not be the same as any other loop_label values in the same scope (ie: when nesting foreach
loops, each loop must have a unique label). This label is used to uniquely identify any given loop level when loops are nested.
The foreach
statement will execute the statements in the body of the loop once for every child. foreach
loops can be nested, and at each iteration the loop_label can be used to extract values from an array or object in the current child using a dynamic parslet. See the examples at the end of this article for a sample implementation showing this in action.
As the foreach
loop iterates over the children, a number of variables are automatically created or updated as follows:
Variable
Value
loop_label.COUNT
The number of times the loop has executed. If the object or array is empty then this variable will have a value of 0.
loop_label.NAME
The name of the current child
loop_label.VALUE
The value of the current child
loop_label.TYPE
The type of the current child
Examples
Basic looping
Consider the following JSON in a file called samples/json/array.json
:
To generate a list of IDs and names from the items array, the following would be used:
Nested looping
To extract values from an array using nested loops:
Given the source JSON in a file called example.json
, the following USE script:
will produce the following output:
Last updated