LogoLogo
3.6.9
3.6.9
  • Introduction
  • Getting started
    • Installation
      • Prerequisites
        • Server requirements
      • On-premises
        • Single-node
          • Directory structure
        • Multi-node
      • Azure Market Place
      • AWS Market Place
    • Tutorials
      • Amazon AWS CUR
      • Amazon AWS CUR (Athena)
      • Azure Stack
      • Azure EA
      • Azure CSP
      • Google Cloud
      • VMware vCloud
      • VMware vCenter
    • How-to guides
      • How to configure receiving a monthly billing report
      • How to automatically trigger a monthly billing report
      • How to update your license
      • How to store contract information with an Account in a report
      • How to automatically send workflow errors as webhooks to a monitoring system
    • Concepts
      • User interface
      • Services
    • Releases
      • Upgrading to version 3
      • Known issues
      • Announcements
      • Archive
  • Reports
    • Accounts
    • Services
    • Instances
    • Summary
    • Budget
  • Services
    • Manage
    • Rates
      • Tiered Services
        • Aggregation Levels and the Account Hierarchy
    • Adjustments
    • Subscriptions
  • ACCOUNTS
    • Budget management
  • Data pipelines
    • Extract
      • Configuration
      • Extractor templates
      • Script basics
      • Parslets
      • Subroutines
        • check_dateformat
        • check_dateargument
        • format_date
        • validate_response
      • Language
        • aws_sign_string
        • basename
        • buffer
        • csv
        • clear
        • decimal_to_ipv4
        • discard
        • encode
        • encrypt
        • environment
        • escape
        • exit_loop
        • foreach
        • generate_jwt
        • get_last_day_of
        • gosub
        • gunzip
        • hash
        • http
        • if
        • ipv4_to_decimal
        • json
        • loglevel
        • loop
        • lowercase
        • match
        • pause
        • print
        • return
        • save
        • set
        • subroutine
        • terminate
        • unzip
        • uppercase
        • uri
        • var
    • Transform
      • Configuration
      • Transformer templates
      • Transform Preview
      • Language
        • aggregate
        • append
        • calculate
        • capitalise
        • convert
        • copy
        • correlate
        • create
        • default
        • delete
        • dequote
        • environment
        • event_to_usage
        • export
        • finish
        • Functions
        • if
        • import
        • include
        • lowercase
        • normalise
        • option
        • rename
        • replace
        • round
        • services
        • set
        • sort
        • split
        • terminate
        • timecolumns
        • timerender
        • timestamp
        • update_service
        • uppercase
        • var
        • where
    • Datasets
    • Lookups
    • Metadata
    • Reports
    • Workflows
  • Administration
    • User management
      • Users
      • Groups
    • Notifications
      • Budget Notifications
      • Report notifications
      • Workflow notifications
    • Settings
      • Global Variables
      • White Labeling
  • Advanced
    • Integrate
      • GUI automation
        • Examples
      • API docs
      • Single sign-on
        • Claims-based identity provisioning: users, Account access and user groups
        • Azure-AD
        • Auth0
        • OKTA
        • OneLogin
        • ADFS
        • LDAP
    • Digging deeper
      • Authentication flows
      • Transformer datadate
      • Dataset lifecycle
      • Config.json
      • Databases
  • Security
    • Security
    • Authentication
      • Token
      • LDAP
      • SAML2
    • Password reset
    • Password policy
    • Announcements
  • Troubleshooting
    • Logs
  • Terms & Conditions
  • Privacy Policy
Powered by GitBook
On this page
  • Syntax
  • Details
  • Examples
  • Basic looping
  • Nested looping

Was this helpful?

Export as PDF
  1. Data pipelines
  2. Extract
  3. Language

foreach

Previousexit_loopNextgenerate_jwt

Last updated 3 years ago

Was this helpful?

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

foreachparsletasloop_label{

`# Zero or more USE script statements go here` 

}

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 ) within the data in a .

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 . 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:

{
    "totalCount" : 2,
    "items" : [
        {
            "name" : "Item number one",
            "id" : "12345678"
        },
        {
            "name" : "Item number two",
            "id" : "ABCDEFGH"
        }
    ]
}

To generate a list of IDs and names from the items array, the following would be used:

buffer data = file "samples/json/array.json"

foreach $JSON{data}.[items] as this_item
{
    print Customer ${this_item.COUNT}: $JSON(this_item).[id] $JSON(this_item).[name]
}

discard {data}

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:

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

var title = $JSON{example}.[title]

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

    # For every child of the 'subvalues' object ...
    foreach $JSON(this_item).[subvalues] as this_subvalue
    {
        var sub_name = ${this_subvalue.NAME}
        var sub_value = ${this_subvalue.VALUE}

        # Render an output line
        print ${title} -> Item: ${item_name} -> Subvalue:${sub_name} = ${sub_value} 
    }
}
discard {example}

will produce the following output:

Example JSON data -> Item: Item number one -> Subvalue:0 = 1
Example JSON data -> Item: Item number one -> Subvalue:10 = 42
Example JSON data -> Item: Item number one -> Subvalue:100 = 73
Example JSON data -> Item: Item number one -> Subvalue:1000 = 100
Example JSON data -> Item: Item number two -> Subvalue:0 = 10
Example JSON data -> Item: Item number two -> Subvalue:10 = 442
Example JSON data -> Item: Item number two -> Subvalue:100 = 783
Example JSON data -> Item: Item number two -> Subvalue:1000 = 1009
parslet
named buffer
dynamic parslet