Skip to content

Range variables

Sometimes you want to run a transform and then do something more with the result, such as some math or a loop over it. Usually you don’t want that intermediate result in the final output; it’s only there for preprocessing. Range variables cover this.

All variables start with @. Writing one as a property name declares and sets it, and removes that node from the output.

{
"@firstVar": "#valueOf($.someInteger)",
"@secondVar": "#valueOf($.someOtherInteger)",
"sum": "@firstVar + @secondVar"
}

#foreach transforms each element of an array using a content template. Its result goes to a named property (into 'name') or into a variable (into @name).

{
"#foreach(@x in $.someArray) into @tempResult": [
{
"intermediateValue": "@x.someInteger * 2"
}
],
"#foreach(@x;@i in @tempResult) into 'actualResult'": [
{
"finalValue": "@x.intermediateValue + 5",
"currentIndex": "@i"
}
]
}

The first loop stores the transformed array in @tempResult and removes the node from the output. The second loop iterates over that intermediate array, transforms it again, and names the final property actualResult.

To get the index as well as the value, declare two variables separated by a semicolon. The left one is the value and the right one is the index.

Variables declared inside a loop’s content template exist only within it, per iteration: they’re redeclared, set, and discarded every time through the loop.

{
"#foreach(@x in $.someArray) into 'finalResult'": [
{
"@scopedVar": "@x.someInteger / 2",
"subtractedValue": "@scopedVar - 3"
}
],
"invalidValue": "@scopedVar"
}

finalResult is populated by the loop, but invalidValue is null because @scopedVar no longer exists outside it.

When #foreach iterates an object, the variable is set to each property value in turn.

{
"#foreach(@x in $.someObject) into 'result'": [
{
"propertyValue": "@x"
}
]
}

A hardcoded property name like propertyValue is overwritten on every iteration. To keep each original property name, use #nameOf on the loop variable as the property name:

{
"#foreach(@x in $.someObject) into 'result'": [
{
"#nameOf(@x)": "@x"
}
]
}