How to Use the Loop Block to Iterate Over a JSON Array Returned from a Data Action in NICE CXone
What You Will Build
- A CXone Studio flow that retrieves a JSON array from a custom Data Action and iterates through each item using the Loop block to process records individually.
- This tutorial uses the NICE CXone Studio visual interface and the CXone Data Action API.
- The programming language covered is JavaScript (for the Data Action logic) and JSON (for the Studio Flow definition).
Prerequisites
- NICE CXone Developer Account: Access to the CXone platform with permissions to create Data Actions and Studio Flows.
- Studio Access: Ability to edit and publish Studio flows.
- Data Action Permissions: Permissions to create and manage custom Data Actions.
- Node.js Runtime: Required if testing the Data Action logic locally (though the primary implementation is within CXone).
- Basic JSON Knowledge: Understanding of JSON arrays and objects.
Authentication Setup
CXone Studio flows run server-side within the NICE CXone infrastructure. Authentication is handled automatically by the platform for internal calls between Studio blocks and Data Actions. However, when defining a Data Action that calls an external API, you must configure OAuth or API Key authentication within the Data Action’s configuration.
For this tutorial, we assume the Data Action retrieves data from an internal CXone source (e.g., a custom database or a previously stored variable) or a pre-configured external service. If your Data Action calls an external REST API, ensure the Authorization header is set in the Data Action’s HTTP request configuration.
No code is required for Studio flow authentication; it is managed via the CXone admin console under Integration > Data Actions.
Implementation
Step 1: Create the Data Action that Returns a JSON Array
Before using the Loop block, you must have a Data Action that returns a structured JSON array. Studio loops require a consistent array structure.
- Navigate to Integration > Data Actions.
- Click Create Data Action.
- Name it
GetUserOrders. - Set the Request Type to
POST(orGETif no body is needed). - In the Response Mapping, ensure the output is mapped to a JSON array.
Here is an example of a custom JavaScript Data Action logic that returns a static JSON array for testing. In production, this would query a database or external API.
// CXone Data Action Logic: GetUserOrders
// This script runs on the CXone server and returns a JSON array.
function main() {
// Simulate fetching data from a database or external API
const orders = [
{
"orderId": "ORD-001",
"product": "Headset",
"quantity": 2,
"status": "Shipped"
},
{
"orderId": "ORD-002",
"product": "Keyboard",
"quantity": 1,
"status": "Processing"
},
{
"orderId": "ORD-003",
"product": "Monitor",
"quantity": 1,
"status": "Delivered"
}
];
// Return the array as the response body
return {
statusCode: 200,
body: JSON.stringify(orders)
};
}
Key Configuration:
- In the Data Action editor, set the Response Format to
JSON. - Ensure the root element of the response is an array
[...]. If the root is an object{...}containing an array, you must map the specific array field in the Studio block.
Step 2: Configure the Data Action Block in Studio
- Open your Studio Flow.
- Drag the Data Action block onto the canvas.
- Select
GetUserOrdersfrom the dropdown. - Configure the Outputs:
- The block will automatically detect the JSON structure.
- Map the output to a variable named
ordersArray. - Ensure the type is set to
ArrayorJSON Objectdepending on the exact response.
Expected Output Variable:
The variable ordersArray will now contain:
[
{"orderId": "ORD-001", "product": "Headset", "quantity": 2, "status": "Shipped"},
{"orderId": "ORD-002", "product": "Keyboard", "quantity": 1, "status": "Processing"},
{"orderId": "ORD-003", "product": "Monitor", "quantity": 1, "status": "Delivered"}
]
Step 3: Configure the Loop Block
The Loop block iterates over the array provided by the Data Action.
- Drag the Loop block onto the canvas.
- Connect it from the Success output of the Data Action block.
- Configure the Loop block:
- Input Array: Select
ordersArray(the output from the Data Action). - Current Item Variable: Name it
currentOrder. This variable will hold the value of the current element in each iteration.
- Input Array: Select
Loop Configuration Details:
- The Loop block automatically handles the iteration index. You can access the current index using
{{loop.index}}if needed. - The
currentOrdervariable will be available within the scope of the Loop block and any blocks connected to its Next output.
Step 4: Process Each Item Inside the Loop
Inside the Loop block, you can add logic to process each order. For example, let us add a Set Variable block to create a formatted message for each order.
- Drag a Set Variable block onto the canvas.
- Connect it from the Next output of the Loop block.
- Configure the Set Variable block:
- Variable Name:
orderMessage - Value:
Order {{currentOrder.orderId}} for {{currentOrder.product}} is {{currentOrder.status}}.
- Variable Name:
This block will execute once for each item in the ordersArray.
Step 5: Accumulate Results (Optional)
If you need to collect results from each iteration, you can use a List variable.
-
Before the Loop block, add a Set Variable block to initialize an empty list:
- Variable Name:
messagesList - Value:
[](empty array)
- Variable Name:
-
Inside the Loop, after setting
orderMessage, add another Set Variable block to append the message:- Variable Name:
messagesList - Value:
{{messagesList + [orderMessage]}}(using JavaScript array concatenation syntax supported in CXone expressions)
- Variable Name:
-
After the Loop block, add a End or Response block to return the final list.
Complete Working Example
Below is a conceptual representation of the Studio Flow JSON structure. While Studio is visual, this JSON illustrates the logical flow and variable mappings.
{
"flowId": "sample-loop-flow",
"name": "Process Orders Loop",
"version": 1,
"blocks": [
{
"id": "start",
"type": "Start",
"outputs": {
"default": "dataActionBlock"
}
},
{
"id": "dataActionBlock",
"type": "DataAction",
"dataActionId": "GetUserOrders",
"outputs": {
"success": "loopBlock",
"error": "endError"
},
"variables": {
"output": "ordersArray"
}
},
{
"id": "loopBlock",
"type": "Loop",
"inputArray": "{{ordersArray}}",
"currentItemVariable": "currentOrder",
"outputs": {
"next": "setOrderMessage",
"end": "endSuccess"
}
},
{
"id": "setOrderMessage",
"type": "SetVariable",
"variableName": "orderMessage",
"value": "Order {{currentOrder.orderId}} for {{currentOrder.product}} is {{currentOrder.status}}.",
"outputs": {
"default": "appendToList"
}
},
{
"id": "appendToList",
"type": "SetVariable",
"variableName": "messagesList",
"value": "{{messagesList + [orderMessage]}}",
"outputs": {
"default": "loopBlock"
}
},
{
"id": "endSuccess",
"type": "End",
"response": {
"body": "{{messagesList}}"
}
},
{
"id": "endError",
"type": "End",
"response": {
"body": "Error fetching orders."
}
}
]
}
Note: In the actual Studio interface, you will drag and drop blocks and configure them via the UI. The JSON above is for reference to understand the logical connections.
Common Errors & Debugging
Error: Loop Block Fails to Iterate
Cause: The input array is null, undefined, or not a valid JSON array.
Fix:
- Check the Data Action response. Ensure it returns a valid JSON array
[...]. - If the Data Action returns an object
{ "orders": [...] }, you must map theordersfield to the Loop input, not the entire response. - Add a Condition block before the Loop to check if the array is empty or null.
Error: Variable Scope Issues
Cause: Attempting to access currentOrder outside the Loop block.
Fix:
- Variables defined inside a Loop (like
currentOrder) are only available within the Loop’s scope. - To use data from the loop outside, accumulate it in a variable defined before the loop (e.g.,
messagesList) as shown in Step 5.
Error: Data Action Timeout
Cause: The Data Action takes too long to respond.
Fix:
- Optimize the Data Action logic.
- Increase the timeout setting in the Data Action block configuration in Studio (if available).
- Ensure external APIs called by the Data Action are responsive.
Error: Invalid JSON in Data Action Response
Cause: The Data Action returns malformed JSON.
Fix:
- Validate the JSON output of the Data Action using a JSON validator.
- Ensure all strings are properly escaped.
- Use
JSON.stringify()in JavaScript Data Actions to ensure valid JSON output.