To Drill Down into JSON (Design Center)

This procedure describes how to use For Each to access nested JSON elements in an object. For Each iterates over and processes each element separately. For example purposes, each time the process repeats, you log the value of the element and the counter. In a real-world situation, instead of a simple log operation, you might insert each element in a database for analysis or perform other operations.

To configure For Each, you use dot notation in the expression to specify the path to the JSON element of interest. For example, to apply some processing to bs in the company object, you set the Collection field to payload.*company.bs. The asterisk prefix accesses all members of company.

In the configuration, you use a default batch size of one because the example data you use consists of only 10 objects. If you have 200 objects and a batch size of 50, the app iterates over 50 objects at a time, returning four separate results, one for each batch.

This procedure builds on the procedures to create a basic Mule app and to add an expression to dynamically change the URL of a request. After performing these procedures, you have HTTP listener and HTTP request in the Consume API flow, and you can perform the following steps to add For Each to the flow.

Proceed to the next step if the app is running. Otherwise, click Run. Execute the flow as follows:

Click Copy Link.

Paste the link in a browser or client, and type /getpath?path=users at the end.

The HTTP Listener hears the request, and starts the app. The JSON Placeholder profiles of all users appear in the browser.

In Design Center, add and configure For Each:

Click after HTTP Request.

Select For Each.

Configure For Each as follows:

In Collection, type the expression, using dot expression, to access the list, array, or map you want to iterate over . For example, type the following expression to access the bs element in company: payload.*company.bs

In Batch Size, accept the default 1.

Accept the defaults rootMessage.

In Counter Variable Name, change the default to drillcounter just for example purposes.

Close For Each.

On the face of the For Each component, click Plus and select Logger. Configure Logger as follows:

In Message, click .

Type the following expression:

vars.drillcounter

Close the Logger.

To the right of and outside of For Each, add another Logger. Configure Logger as follows:

In Message, click .

Type the following expression:

payload

Click Run, and execute the flow as described in step 1. Check the logs to see 10 messages, one for each iteration followed by the last message that contains the original input to the flow.