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){

`# Statements`

} [else {

`# Statements`

}]

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:

if (($JSON{example}.[status] == "OK") || (${override} == "enabled")) { 
    # Execute if the status is "OK" or if we have set ${override} to "enabled"
}

Example

Given the source JSON in a file called example.json, the following USE script:

var JSON_dir = "examples\json"
buffer example = FILE "${JSON_dir}\doc.json"

var title = 

# For every element in the 'items' array ...
foreach $JSON{example}.[items] as this_item
{
    # Extract the item name and id
    var item_name = $JSON(this_item).[name]
    var sub_id = $JSON(this_item).[id]

    if (${sub_id} == 02) {
        # For every child of the 'subvalues' object ...
        foreach $JSON(this_item).[subvalues] as this_subvalue
        {
            # Get the subvalue name and value
            var sub_name = ${this_subvalue.NAME}
            var sub_value = ${this_subvalue.VALUE}

            # Render an output line
            print ${title} (id:${sub_id} -> Item: ${item_name} -> Subvalue:${sub_name} = ${sub_value} 
        }
    } else {
            print Skipping unwanted id: ${sub_id}
        }

}
discard {example}
terminate

will produce the following output:

    Skipping unwanted id: 01
    Example JSON data (id: 02) -> Item: Item number two -> Subvalue:0 = 10
    Example JSON data (id: 02) -> Item: Item number two -> Subvalue:10 = 442
    Example JSON data (id: 02) -> Item: Item number two -> Subvalue:100 = 783
    Example JSON data (id: 02) -> Item: Item number two -> Subvalue:1000 = 1009

Last updated