How to use the Loop block to iterate over a JSON array returned from a Data Action

How to use the Loop block to iterate over a JSON array returned from a Data Action

What You Will Build

  • You will build a NICE CXone Flow that retrieves a list of customer orders from an external API via a Data Action and iterates over each order to calculate a total refund amount.
  • You will use the NICE CXone Flow Designer Loop block and the HTTP Data Action connector.
  • You will configure the JSON parsing logic in the Loop block to handle array iteration correctly, avoiding common scope and indexing errors.

Prerequisites

  • NICE CXone Account: Access to the Flow Designer with permissions to create and publish flows.
  • Data Action Endpoint: A valid HTTP endpoint that returns a JSON array. For this tutorial, we assume a local or public endpoint like https://api.example.com/orders that returns:
    [
      { "orderId": "1001", "amount": 50.00, "status": "cancelled" },
      { "orderId": "1002", "amount": 120.50, "status": "cancelled" }
    ]
    
  • Flow Designer Access: Ability to drag and drop blocks and configure JSON mappings.
  • Understanding of JSON Paths: Familiarity with dot notation ($.items[0].id) and array iteration concepts.

Authentication Setup

For this tutorial, authentication is handled within the NICE CXone platform. The Data Action block requires an HTTP connector. If your target API requires authentication, you must configure the HTTP Connector in the NICE CXone Administration > Integrations > HTTP Connectors section before building the flow.

  1. Navigate to Administration > Integrations > HTTP Connectors.
  2. Click Add.
  3. Enter a Name (e.g., “ExternalOrderAPI”).
  4. Select the Authentication Type (e.g., “None” for public endpoints, “Basic Auth”, or “OAuth 2.0”).
  5. Save the connector.

In the Flow Designer, you will reference this connector by name when configuring the Data Action block.

Implementation

Step 1: Configure the Data Action to Retrieve the JSON Array

The first step is to fetch the data. The Loop block cannot iterate over raw string data; it requires a structured JSON object or array. The Data Action block must be configured to parse the response body as JSON.

  1. Drag a Data Action block into the Flow Designer.
  2. Select the HTTP connector type.
  3. Choose the connector created in the Prerequisites step (e.g., “ExternalOrderAPI”).
  4. Configure the Request:
    • Method: GET
    • URL: https://api.example.com/orders
    • Headers: Add Accept: application/json if required by your API.
  5. Configure the Response:
    • Response Type: Select JSON.
    • Result Field Name: Set this to orderResponse. This is the variable name that will hold the parsed JSON in the flow context.

Critical Configuration Note:
If the API returns an array directly (e.g., [ {...}, {...} ]), the orderResponse variable will be an array. If the API returns an object containing an array (e.g., { "data": [ {...} ] }), you must extract the array in the next step or map it correctly in the Loop block. For this tutorial, we assume the API returns a direct JSON array.

Expected Response:

[
  {
    "orderId": "1001",
    "amount": 50.00,
    "status": "cancelled"
  },
  {
    "orderId": "1002",
    "amount": 120.50,
    "status": "cancelled"
  }
]

Step 2: Configure the Loop Block to Iterate Over the Array

The Loop block is designed to iterate over JSON arrays. It creates a temporary scope for each iteration, allowing you to access the current item’s properties.

  1. Drag a Loop block into the Flow Designer.
  2. Connect the Success output of the Data Action block to the Start input of the Loop block.
  3. Configure the Loop Block properties:
    • Input Data: Select the variable containing the JSON array. In this case, select orderResponse.
    • Iteration Variable Name: Enter a name for the current item, e.g., currentOrder. This variable will represent the individual object in each iteration.
    • Loop Type: Select For Each. This is the standard mode for iterating over all items in an array.

Understanding the Scope:
Inside the Loop block, the variable currentOrder is available. If the orderResponse array contains objects with fields orderId and amount, you can access them inside the loop using currentOrder.orderId and currentOrder.amount.

Edge Case: Nested Arrays:
If your JSON structure is nested (e.g., orderResponse is an object with a field items that is an array), you must use JSON Path notation in the Input Data field.

  • Example: If orderResponse is { "items": [ {...} ] }, set Input Data to orderResponse.items.

Step 3: Process Each Item Within the Loop

Now that the Loop block is iterating, you need to perform logic on each item. For this tutorial, we will calculate a running total of refund amounts.

  1. Add an Update Variable block inside the Loop block.
    • Connect the Next output of the Loop block to the input of the Update Variable block.
    • Connect the Success output of the Update Variable block back to the Next input of the Loop block to create the iteration cycle.
  2. Configure the Update Variable block:
    • Variable Name: totalRefund
    • Operation: Add
    • Value: currentOrder.amount

Initialization:
Before the loop starts, you must initialize the totalRefund variable to 0.

  1. Drag an Update Variable block before the Data Action or immediately after.
  2. Set Variable Name to totalRefund.
  3. Set Value to 0.

Logic Flow:

  1. Initialize totalRefund = 0.
  2. Fetch orderResponse (Array of orders).
  3. Start Loop:
    • Iteration 1: currentOrder = { "orderId": "1001", "amount": 50.00 }. totalRefund = 0 + 50.00 = 50.00.
    • Iteration 2: currentOrder = { "orderId": "1002", "amount": 120.50 }. totalRefund = 50.00 + 120.50 = 170.50.
  4. End Loop.

Step 4: Handle Loop Completion and Error States

The Loop block has three outputs:

  • Next: Used to continue iterating.
  • Complete: Triggered when all items have been processed.
  • Error: Triggered if the input data is not a valid array or if an error occurs during iteration.
  1. Connect the Complete output of the Loop block to a Say block or Update Variable block to use the final totalRefund value.
    • Example: Drag a Say block. Set the text to “Total refund amount is ${totalRefund}.”
  2. Connect the Error output of the Loop block to a Handle Error block or a Say block that informs the user of a processing failure.
    • Example: “Sorry, we could not process your orders.”

Debugging Tip:
If the Loop block immediately goes to the Error output, check the Input Data configuration. Ensure that the variable you selected actually contains a JSON array at runtime. You can use the Debug mode in Flow Designer to inspect the variable values.

Complete Working Example

Below is the step-by-step configuration for the complete flow.

Flow Structure

  1. Start Node
  2. Update Variable (Initialize totalRefund = 0)
  3. Data Action (HTTP GET to https://api.example.com/orders)
    • Connector: ExternalOrderAPI
    • Response Type: JSON
    • Result Field: orderResponse
  4. Loop
    • Input Data: orderResponse
    • Iteration Variable: currentOrder
    • Loop Type: For Each
  5. Update Variable (Inside Loop)
    • Variable: totalRefund
    • Operation: Add
    • Value: currentOrder.amount
  6. Say (After Loop Complete)
    • Text: “Your total refund is ${totalRefund}.”
  7. Say (After Loop Error)
    • Text: “An error occurred while processing your orders.”

Connections

  • Start → Update Variable (Init) → Data Action → Loop
  • Loop (Next) → Update Variable (Add) → Loop (Next) [Cycle]
  • Loop (Complete) → Say (Success)
  • Loop (Error) → Say (Error)

JSON Mapping Details

In the Loop block configuration:

  • Input Data: orderResponse
  • Iteration Variable Name: currentOrder

In the Update Variable block (inside loop):

  • Value: currentOrder.amount

Expected Runtime Behavior

  1. The flow starts.
  2. totalRefund is set to 0.
  3. The Data Action calls the API and receives:
    [
      { "orderId": "1001", "amount": 50.00 },
      { "orderId": "1002", "amount": 120.50 }
    ]
    
  4. The Loop block initializes with currentOrder = first item.
  5. totalRefund becomes 50.00.
  6. Loop continues to second item.
  7. totalRefund becomes 170.50.
  8. Loop completes.
  9. The system says: “Your total refund is 170.5.”

Common Errors & Debugging

Error: Loop Block Fails with “Invalid Input Data”

What causes it:
The variable specified in the Input Data field of the Loop block is not a JSON array. It might be:

  • A JSON object (e.g., { "items": [...] } instead of [...]).
  • A string representation of JSON (not parsed).
  • Null or undefined.

How to fix it:

  1. Check the API response structure. If the response is an object, extract the array using JSON Path.
    • Example: If the response is { "data": [ {...} ] }, set Input Data to orderResponse.data.
  2. Ensure the Data Action block has Response Type set to JSON. If it is set to Text, the result will be a string, and the Loop block cannot iterate over it.
  3. Use the Debug feature in Flow Designer to inspect the variable value before the Loop block. Verify it is an array.

Error: Iteration Variable Properties Are Undefined

What causes it:
The properties you are accessing in the iteration variable (e.g., currentOrder.amount) do not exist in the JSON object.

How to fix it:

  1. Verify the exact field names in the API response. JSON keys are case-sensitive.
  2. If the API returns inconsistent structures, add a Condition block inside the loop to check if the property exists.
    • Example: Condition currentOrder.amount != null. If true, proceed to update variable. If false, skip.

Error: Infinite Loop or Performance Issues

What causes it:
The Loop block is configured incorrectly, causing it to not advance or to process an excessively large array.

How to fix it:

  1. Ensure the Next output of the internal logic connects back to the Next input of the Loop block. If it connects to the Start input, it will restart the loop from the beginning.
  2. If the array is very large (e.g., >10,000 items), consider using pagination in the Data Action or processing the data in batches. The Loop block can handle large arrays, but it may impact flow execution time.

Error: Variable Scope Issues

What causes it:
Variables updated inside the Loop block are not accessible outside the Loop block.

How to fix it:
In NICE CXone Flows, variables updated inside a Loop block using Update Variable are generally available in the parent scope after the loop completes. However, ensure you are using the same variable name.

  • If you create a new variable inside the loop, it may not persist. Always use Update Variable on a pre-existing variable or a variable initialized before the loop.

Official References