Skip to main content

Dataweave My Practice

 https://www.caeliusconsulting.com/blogs/transforming-messages-with-dataweave/

  1. Add 1 to each value in the array [1,2,3,4,5]

           Ans:

%dw 2.0
output application/json
---
payload map $+1



 2)Get a list of ids from:

            

 [ { "id": 1, "name": "Archer" },
  { "id": 2, "name": "Cyril"  },
  { "id": 3, "name": "Pam"    } ]


%dw 2.0
output application/json
---
payload map $.id


 

___________________________________________________________________________________

Example 1: Using the input data, we'll produce a patterned output based on the given array.

Input:


    [
	{"name": "Roger"	},
	{"name": "Michael"	},
	{"name": "Harris"	}
     ]


Output:
          [
  {
    "user 1": "Roger"
  }, 
  {
    "user 2": "Micheal"
  }, 
  {
    "user 3": "Harris"
  }
        ]


Dataweave code:

Solution1: without map

%dw 2.0
output application/json
---
{
"user1":payload[0].name,
"user2":payload[1].name,
"user3":payload[2].name
}


Solution2: with map

%dw 2.0
output application/json
---
 
payload map((item,index)->{
("user" ++" "++ index+1): item.name
})

____________________________________________________________________________

Example 2: Given two arrays, [1,2,3,4,5,6,7] and [4,5,6,7,1], we’ll merge into a single array without duplicates, [1,2,3,4,5,6,7]:


Dataweave Code:



%dw 2.0
output application/json
var array1= [1,2,3,4,5,6,7,9,10]
var array2= [4,5,6,7,1,10]
var sum=array1 ++ array2
---
sum distinctBy ((item, index) -> item )



OutPut:
[
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  9,
  10
]

____________________________________________________________________________________
Example 3: From the object, we’ll remove the “last name” and “first name” key-value pair.
Input:
{
        "first name": "Keith",
       "last name": "Peters",
        "age": 25
        
}
Output:

{
 "age": 25
}

Solution1: Without filterobject

%dw 2.0
output application/json
---
payload -- payload.&"first name" -- payload.&"last name"


Solution2: With filterObject filter

%dw 2.0
output application/json
---
payload filterObject ((value, key, index) -> (key as String != "first name" and key as String !="last name") )



Example 4: From the array [1,2,3,’a’,’b’,'c'], remove 2 and b and c .

Solution 1:
%dw 2.0
output application/json
var array1=[1, 2, 3, 'a','b', 'c']
---
array1 - 2 -'a' -'c'

Solution 2:

%dw 2.0
output application/json
var array1=[1, 2, 3, 'a','b', 'c']
---
array1 -- [2 ,'a' ,'c']


Output is:
[
1,
3,
"b"
]

_____________________________________________________________________________________


Example 5: Given the below JSON, transform all names to uppercase.

Input Payload :

    [
    {"name": "Sravan"    },
    {"name": "Kumar"   },
    {"name": "Singamaneni"   }
    ]

Output Pattern:

[
 {
   "NAME": "SRAVAN"
 },
 {
   "NAME": "KUMAR"
 },
 {
   "NAME": "SINGAMANENI"
 }
]

Expression Used to Transform:


%dw 2.0
output application/json

---
payload map ((item, index) ->
NAME : upper(item.name) )



______________________________________________________________________________________

Example 6: Retrieve all the records of users with the age greater than 20.

[
{
  "name": "Chris Jordan",
  "age": "19"
},
{
  "name": "Glenn Maxwell",
  "age": "24"
},
{
  "name": "Mike",
  "age": "20"
}
]



DWcode:

%dw 2.0
output application/json

---
payload filter ((item, index) ->
item.age > 20
)


Output:

[
{
"name": "Glenn Maxwell",
"age": "24"
}
]


__________________________________________________________________________________


Example 7: Retrieve the average age of persons in the input payload.

[
{
  "name": "Sravan",
  "age": "19"
},
{
  "name": "kumar",
  "age": "24"
},
{
  "name": "singamaneni",
  "age": "20"
}
]



Exercise 1: 

Basic Absolute Value Transformation

Write a DataWeave script that converts a list of integers into their absolute values.

Input:

[-4, 12, -9, 5, -3]

Expected Output:

[4, 12, 9, 5, 3]

Exercise 2:

Absolute Value with Mixed Data

You are given a JSON object where the values are mixed between positive and negative numbers.

Transform this object so that each value is replaced by its absolute value.

Input:

{ "a": -8, "b": 15, "c": -6, "d": 9 }

Expected Output:

{ "a": 8, "b": 15, "c": 6, "d": 9 }


Exercise 3:

Absolute Value and Conditional Logic

Given an array of numbers, return an array of strings where the string is "Positive" if the absolute value of the number is greater than 5, otherwise "Negative".

Input:

[-7, 3, -10, 1, 6]

Expected Output:

["Positive", "Negative", "Positive", "Negative", "Positive"]


Exercise 4: Array of Objects Transformation

You are given an array of objects where each object represents a transaction with a balance field. Write a DataWeave transformation that replaces the balance value in each object with its absolute value.

Input:

[

{ "id": 1, "balance": -100 }, { "id": 2, "balance": 50 }, { "id": 3, "balance": -30 } ]

Expected Output:

[

{ "id": 1, "balance": 100 }, { "id": 2, "balance": 50 }, { "id": 3, "balance": 30 } ]

Exercise 5: Summing Absolute Values

You are given an array of numbers, both positive and negative. Write a DataWeave transformation that returns the sum of the absolute values of the array elements.

Input:

[-8, 12, -3, 5, -10]

Expected Output:

38

Exercise 6: Nested Structures

You are given a nested object where the inner objects contain positive and negative values. Write a DataWeave script that transforms all the numbers inside the nested structure into their absolute values.

Input:

{
"account": { "id": 101, "transactions": { "t1": -500, "t2": 200, "t3": -150 } } }

Expected Output:

{
"account": { "id": 101, "transactions": { "t1": 500, "t2": 200, "t3": 150 } } }

Exercise 7: Handling Empty Arrays

Create a DataWeave script that takes an array of numbers and outputs the absolute values of the numbers, but if the input array is empty, the output should be the string "No values".

Input 1:

[-1, -2, 3]

Expected Output 1:

[1, 2, 3]

Input 2:

[]

Expected Output 2:

"No values"

Exercise 8: Absolute Values from CSV

You are given a CSV input of expenses (some of them negative due to refunds). Write a DataWeave transformation to convert this CSV to JSON, where all expense values are represented as absolute values.

Input (CSV):

"category","amount"
"food",-50 "travel",100 "clothes",-20

Expected Output (JSON):

[
{ "category": "food", "amount": 50 }, { "category": "travel", "amount": 100 }, { "category": "clothes", "amount": 20 } ]


1. Basic Average of Numbers

Write a DataWeave script that calculates the average of a list of integers.

Input:

[10, 20, 30, 40, 50]

Expected Output:

30

2. Average of Mixed Numbers (Positive and Negative)

Write a DataWeave script to compute the average of an array containing both positive and negative numbers.

Input:

[-10, 5, -15, 20, 30]

Expected Output:

6

3. Average of Object Properties

You are given an array of objects, each representing a student's score in a test. Write a DataWeave script to calculate the average score.

Input:

[
{ "student": "Alice", "score": 85 }, { "student": "Bob", "score": 70 }, { "student": "Charlie", "score": 90 } ]

Expected Output:

81.66666666666667

4. Handling Null or Missing Values in Average

You are given an array of numbers with some null values. Write a DataWeave transformation that ignores the null values and calculates the average of the remaining numbers.

Input:

[10, null, 25, null, 40]

Expected Output:

25

5. Average of Nested Structures

You are given an array of objects where each object contains a nested list of numbers. Write a DataWeave transformation to calculate the average of all numbers in the nested lists.

Input:

[
{ "id": 1, "values": [10, 20, 30] }, { "id": 2, "values": [5, 15, 25] }, { "id": 3, "values": [100, 200] } ]

Expected Output:

47.22222222222222

6. Conditional Average Calculation

Write a DataWeave script that calculates the average of numbers in an array, but only include numbers that are greater than 10 in the calculation.

Input:

[5, 12, 8, 20, 3, 15]

Expected Output:

15.666666666666666

7. Average of Even Numbers

Given an array of numbers, write a DataWeave script that calculates the average of only the even numbers.

Input:

[1, 2, 3, 4, 5, 6, 7, 8]

Expected Output:

5

8. Average with Empty Array Handling

Write a DataWeave script that calculates the average of an array, but if the array is empty, it should return 0 as the output.

Input 1:

[10, 20, 30]

Expected Output 1:

20

Input 2:

[]

Expected Output 2:

0

9. Average of CSV Data

You are given a CSV file containing people's ages. Write a DataWeave transformation that calculates the average age from the CSV data.

Input (CSV):

"name","age"
"Alice",25 "Bob",30 "Charlie",35

Expected Output (JSON):

30

10. Average of Filtered Data

You are given an array of products where each product has a price. Write a DataWeave transformation that calculates the average price, but only include products that are more expensive than $50.

Input:


[ { "name": "Product1", "price": 40 }, { "name": "Product2", "price": 60 }, { "name": "Product3", "price": 80 }, { "name": "Product4", "price": 30 } ]

Expected Output:

70

11. Grouping Data and Calculating Averages

You are given a list of employees with their department and salary information. Write a DataWeave script to calculate the average salary per department.

Input:

[
{ "name": "Alice", "department": "HR", "salary": 40000 }, { "name": "Bob", "department": "HR", "salary": 50000 }, { "name": "Charlie", "department": "IT", "salary": 60000 }, { "name": "David", "department": "IT", "salary": 70000 } ]

Expected Output:

{
"HR": 45000, "IT": 65000 }

12. Weighted Average

You are given an array of grades, where each grade has a corresponding weight. Write a DataWeave script that calculates the weighted average of the grades.

Input:

[
{ "grade": 85, "weight": 0.4 }, { "grade": 90, "weight": 0.6 } ]

Expected Output:

88


Question 1: Rounding Prices

Given a payload of products with prices, use the ceil function to round each product's price up to the nearest integer.

Input Payload:

{
"products": [ { "name": "Laptop", "price": 999.95 }, { "name": "Mouse", "price": 19.45 }, { "name": "Keyboard", "price": 45.88 } ] }

Expected Output:

{
"products": [ { "name": "Laptop", "roundedPrice": 1000 }, { "name": "Mouse", "roundedPrice": 20 }, { "name": "Keyboard", "roundedPrice": 46 } ] }

Question 2: Rounding Negative Numbers

You have a list of both positive and negative decimal numbers. Write a DataWeave transformation that rounds all the numbers up using the ceil function.

Input Payload:

[-10.7, -3.2, 1.5, 4.4]

Expected Output:

[-10, -3, 2, 5]

Question 3: Conditional Rounding

Given a payload of numbers, use the ceil function to round only the numbers that are greater than 10. For numbers less than or equal to 10, return the original value.

Input Payload:

[8.7, 11.3, 5.9, 14.1, 10]

Expected Output:

[8.7, 12, 5.9, 15, 10]

Question 4: Rounding in Nested Structures

You have a payload of customer orders, and each order has multiple items with prices. Use the ceil function to round up the price of each item.

Input Payload:


{ "orders": [ { "orderId": "123", "items": [ { "name": "Book", "price": 12.45 }, { "name": "Pen", "price": 1.75 } ] }, { "orderId": "456", "items": [ { "name": "Bag", "price": 29.99 }, { "name": "Shoes", "price": 49.50 } ] } ] }

Expected Output:

{
"orders": [ { "orderId": "123", "items": [ { "name": "Book", "roundedPrice": 13 }, { "name": "Pen", "roundedPrice": 2 } ] }, { "orderId": "456", "items": [ { "name": "Bag", "roundedPrice": 30 }, { "name": "Shoes", "roundedPrice": 50 } ] } ] }

Question 5: Combining Functions

You have a list of sales amounts for different days. Use the ceil function to round up each sales amount, but only if the original amount is not an integer. Otherwise, leave it unchanged.

Input Payload:

[100.0, 199.99, 50.5, 75.0, 23.12]

Expected Output:

[100, 200, 51, 75, 24]

Question 6: Rounding Inside a Conditional Logic

For a list of transactions, round the transaction amount up only if it is below 50. For amounts equal to or greater than 50, return the original amount.

Input Payload:

[45.7, 100.0, 12.9, 51.3, 30.4]

Expected Output:

[46, 100, 13, 51.3, 31]

Question 7: Handling Arrays with Mixed Data Types

You have a mixed array of numbers and strings. Round up only the numbers using ceil while leaving the strings unchanged.

Input Payload:

[2.9, "hello", 7.1, "world", 3.2]

Expected Output:

[3, "hello", 8, "world", 4]

Question 8: Rounding and Formatting Prices

You have a list of product prices, and you want to round them up and format them as strings with a dollar sign prefix (e.g., $5).

Input Payload:


[3.45, 6.99, 1.11, 2.95]

Expected Output:


["$4", "$7", "$2", "$3"]



Comments

Popular posts from this blog

Mulesoft Dataweave Practice Questions-2025

1. map (Transform elements in an array or object) Map an array of numbers to their squares: Input: [1, 2, 3, 4] Output: [1, 4, 9, 16] Dataweave %dw 2.0 output application/json --- payload map ($*$) Convert an array of strings to uppercase: Input: ["apple", "banana", "cherry"] Output: ["APPLE", "BANANA", "CHERRY"] Prefix all keys in an object with "key_": Input: {"name": "John", "age": 25} Output: {"key_name": "John", "key_age": 25} Map an array of objects to only include specific fields: Input: [ {"name": "John", "age": 25, "city": "New York"}, {"name": "Jane", "age": 30, "city": "Los Angeles"} ] Output: [{"name": "John", "city": "New York"}, {"name": "Jane", "city": "Los Angeles...

Mule Interview Questions

### **1. Core MuleSoft Concepts** #### **What is MuleSoft, and what are its key components?** - **MuleSoft** is an integration platform that enables organizations to connect applications, data, and devices seamlessly. - **Key Components**:   - **Anypoint Platform**: The core platform for designing, building, and managing APIs and integrations.   - **Anypoint Studio**: The IDE for developing Mule applications.   - **Anypoint Exchange**: A repository for sharing APIs, templates, and connectors.   - **Runtime Engine**: Executes Mule applications.   - **API Manager**: Manages and secures APIs.   - **DataWeave**: Transformation language for data mapping. #### **Explain the API-led connectivity approach in MuleSoft.** - **API-led connectivity** is a method of connecting data and applications through reusable APIs. - It consists of three layers:   1. **System APIs**: Expose data from core systems.   2. **Process APIs**: Orchestrate data and business logi...