Translate

Thursday 14 March 2024

How to fetch keys & values of an object ? in MuleSoft 123

 How to fetch keys & values of an object ? in MuleSoft


Here are two effective methods to fetch keys and values of an object in MuleSoft 4:

Method 1: Using DataWeave:

DataWeave provides a comprehensive approach for working with objects and their properties. Here's how to achieve this:

a) Extracting Keys:



%dw 2.0
---
// Sample object
var data = {
  "name": "John",
  "age": 30,
  "city": "New York"
};

// Get all keys as an array
var keys = data.keys()

b) Extracting Values:



%dw 2.0
---
// Get all values as an array
var values = data.values()

Explanation:

  • Define a sample object (data) containing key-value pairs.

  • The keys function returns an array containing all the keys present in the object.

  • The values function returns an array containing all the corresponding values associated with the respective keys.

Method 2: Using MEL (Message Expression Language):

MEL offers a basic approach for iterating through objects. Here's how to access keys and values:

a) Extracting Keys:


XML


#[payload.keySet().toArray()]

b) Extracting Values:


XML


#[payload.values().toArray()]

Explanation:

  • The keySet method on the payload object returns a Set containing all the keys.

  • toArray converts the Set to an array for easier manipulation.

  • Similarly, the values method retrieves the values as a collection, and toArray converts it to an array.

Choosing the Right Approach:

  • DataWeave: This is the preferred method due to its clarity, flexibility, and ability to handle nested objects or perform further processing on the extracted keys and values.

  • MEL: While functional for basic scenarios, MEL expressions can become complex for intricate object manipulation or conditional logic.

Additional Considerations:

  • Ensure the payload is a valid JSON object before applying these methods.

  • Error handling can be incorporated within DataWeave or MEL to gracefully handle cases where the payload might not be in the expected format.

Here are some helpful resources for further reference:

Remember that DataWeave offers a more powerful and versatile approach for working with objects and their properties in MuleSoft 4.


No comments:

Post a Comment

Note: only a member of this blog may post a comment.