Search…
if
The if statement is used to conditionally execute one or more statements. In conjunction with an optional else statement it can cause one or other of two blocks of statements to be executed depending on whether an expression is true or false.

Syntax

if(expression){
1
`# Statements`
Copied!
} [else {
1
`# Statements`
Copied!
}]

Details

If the condition evaluates to true, then the first block of statements is executed, and the second block (if present) is skipped over. If the condition evaluates to false then the first block of statements is skipped and the second block (if present) is executed.
The opening { character at the start of each block may be placed on a line of its own if preferred but the closing } must be on a line of its own.
Multiple conditions can be used in a single expression and combined with the boolean operators && or || (for AND and OR respectively) so long as each condition is enclosed in braces. For example:
1
if (($JSON{example}.[status] == "OK") || (${override} == "enabled")) {
2
# Execute if the status is "OK" or if we have set ${override} to "enabled"
3
}
Copied!

Example

Given the source JSON in a file called example.json, the following USE script:
1
var JSON_dir = "examples\json"
2
buffer example = FILE "${JSON_dir}\doc.json"
3
4
var title =
5
6
# For every element in the 'items' array ...
7
foreach $JSON{example}.[items] as this_item
8
{
9
# Extract the item name and id
10
var item_name = $JSON(this_item).[name]
11
var sub_id = $JSON(this_item).[id]
12
13
if (${sub_id} == 02) {
14
# For every child of the 'subvalues' object ...
15
foreach $JSON(this_item).[subvalues] as this_subvalue
16
{
17
# Get the subvalue name and value
18
var sub_name = ${this_subvalue.NAME}
19
var sub_value = ${this_subvalue.VALUE}
20
21
# Render an output line
22
print ${title} (id:${sub_id} -> Item: ${item_name} -> Subvalue:${sub_name} = ${sub_value}
23
}
24
} else {
25
print Skipping unwanted id: ${sub_id}
26
}
27
28
}
29
discard {example}
30
terminate
Copied!
will produce the following output:
1
Skipping unwanted id: 01
2
Example JSON data (id: 02) -> Item: Item number two -> Subvalue:0 = 10
3
Example JSON data (id: 02) -> Item: Item number two -> Subvalue:10 = 442
4
Example JSON data (id: 02) -> Item: Item number two -> Subvalue:100 = 783
5
Example JSON data (id: 02) -> Item: Item number two -> Subvalue:1000 = 1009
Copied!
Last modified 2yr ago
Export as PDF
Copy link