Skip to content

EduardaSRBastos/dataweave-exercises

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 

Repository files navigation

DataWeave Exercises


Table of Contents


Exercises from Medium - Rahul Kumar

Table of Exercises

Exercise #1 - First Letter of Each Word Exercise #2 - Name and Birth Year Exercise #3 - Numbers to Strings Exercise #4 - Format Date Exercise #5 - Reverse Order
Exercise #6 - Flatten Nested Array Exercise #7 - Combine Arrays by ID Exercise #8 - Unique Items in Array Exercise #9 - Number of Days Between Two Dates Exercise #10 - Merge Array of Objects into One Object
Exercise #11 - Total Amount for Each Month Exercise #12 - Convert 12-Hour to 24-Hour Format Exercise #13 - Total Duration Exercise #14 - Unique Words Exercise #15 - Reorganize Structure
Exercise #16 - Transform Object Fields Exercise #17 - Convert Temperature Exercise #18 - Add Fields to Objects Exercise #19 - Total Amount

Exercises

Exercise #1 - First Letter of Each Word

DataWeave Playground

Input
{
  "fullName": "Nagaraju Kshathriya Raghunathrao"
}
Script
%dw 2.0
output application/json
---
Initial: payload.fullName splitBy  " " map ($[0]) joinBy ""

Exercise #2 - Name and Birth Year

DataWeave Playground

Input
[
  {"name": "John", "age": 25},
  {"name": "Alice", "age": 30},
  {"name": "Bob", "age": 22}
]
Script
%dw 2.0
output application/json
---
payload map ((item) -> {
  fullName: item.name,
  birthYear: (now().year - 1) - item.age
})

Exercise #3 - Numbers to Strings

DataWeave Playground

Input
[1, 2, 3, 4, 5]
Script
%dw 2.0
output application/json  
---
"Numbers to Strings": payload map $ as String

Exercise #4 - Format Date

DataWeave Playground

Input
"2022-01-01"
Script
%dw 2.0
output application/json  
---
"Formatted Date": payload as Date as String {format: "dd-MMM-yyyy"}

Exercise #5 - Reverse Order

DataWeave Playground

Input
["apple", "banana", "orange", "grape"]
Script
%dw 2.0
output application/json  
---
"Reverse Order": (payload orderBy $)[-1 to 0]

Exercise #6 - Flatten Nested Array

DataWeave Playground

Input
[1, [2, [3, 4], 5], 6]
Script
%dw 2.0
output application/json 

fun flatArray(array) =
  array map ((item) -> 
    if (item is Array)
      flatten(item)
    else
      item) 
  then flatten($)
---
// Same result: flatten(flatten(payload))
"Flatten Array": flatArray(payload)

Exercise #7 - Combine Arrays by ID

DataWeave Playground

Input
{
  "input1": [
    { "id": 1, "name": "Alice" },
    { "id": 2, "name": "Bob" }
  ],
  "input2": [
    { "id": 1, "age": 25 },
    { "id": 2, "age": 30 }
  ]
}
Script
%dw 2.0
output application/json  
---
payload.input1 map ((input1Item) -> {
  id: input1Item.id,
  name: input1Item.name,
  age: (payload.input2 filter ((input2Item) -> input2Item.id == input1Item.id)).age[0]
})

Exercise #8 - Unique Items in Array

DataWeave Playground

Input
["2021", "1994", "2034", "2032", "2021", "2022", "1995", "2032"]
Script
%dw 2.0
output application/json  
---
"Unique Years": payload distinctBy $

Exercise #9 - Number of Days Between Two Dates

DataWeave Playground

Input
{
  "startDate": "2022-01-01",
  "endDate": "2022-01-10"
}
Script
%dw 2.0
output application/json  
---
Days: daysBetween(payload.startDate, payload.endDate)

Exercise #10 - Merge Array of Objects into One Object

DataWeave Playground

Input
[
  {"name": "Alice"},
  {"age": 25},
  {"city": "New York"}
]
Script
%dw 2.0
output application/json  
---
{ (payload) }

Exercise #11 - Total Amount for Each Month

DataWeave Playground

Input
[
  {"date": "2022-01-05", "amount": 100},
  {"date": "2022-01-15", "amount": 150},
  {"date": "2022-02-10", "amount": 200},
  {"date": "2022-02-25", "amount": 120}
]
Script
%dw 2.0
output application/json  
---
"Total Each Month": payload groupBy ($.date.month as String {format: "00"}) mapObject ((value, key) -> 
  (key): {
    total: sum(value.amount)
  }
)

Exercise #12 - Convert 12-Hour to 24-Hour Format

DataWeave Playground

Input
["02:30 PM", "08:45 AM", "05:15 PM"]
Script
%dw 2.0
output application/json  
---
"12H to 24H": payload map ((item, index) -> item as LocalTime {format: "hh:mm a"} as String {format: "HH:mm"})

Exercise #13 - Total Duration

DataWeave Playground

Input
[
  {"title": "Clip1", "duration": "00:30"},
  {"title": "Clip2", "duration": "01:15"},
  {"title": "Clip3", "duration": "00:45"}
]
Script
%dw 2.0
output application/json  
---
"Total Duration": sum(payload.duration map ( 
  do {
    var parts = $ splitBy ":"
    ---
    (parts[0] + parts[1] / 60) as Number
}))

Exercise #14 - Unique Words

DataWeave Playground

Input
"Even if they are djinns, I will get djinns that can outdjinn them."
Script
%dw 2.0
output application/json  
---
"Unique Words": payload filter $ != "," splitBy  " " distinctBy $

Exercise #15 - Reorganize Structure

DataWeave Playground

Input
{
  "books": [
    {
      "title": "The Alchemist",
      "genre": "Fiction",
      "author": {
        "name": "Paulo Coelho",
        "birthYear": 1947
      }
    },
    {
      "title": "Sapiens",
      "genre": "Non-Fiction",
      "author": {
        "name": "Yuval Noah Harari",
        "birthYear": 1976
      }
    },
    {
      "title": "To Kill a Mockingbird",
      "genre": "Fiction",
      "author": {
        "name": "Harper Lee",
        "birthYear": 1926
      }
    },
    {
      "title": "The Lean Startup",
      "genre": "Business",
      "author": {
        "name": "Eric Ries",
        "birthYear": 1978
      }
    },
    {
      "title": "The Great Gatsby",
      "genre": "Fiction",
      "author": {
        "name": "F. Scott Fitzgerald",
        "birthYear": 1896
      }
    }
  ]
}
Script
%dw 2.0
output application/json  
---
genres: (payload.books groupBy $.genre) pluck ((value, key) -> {
  name: key,
  authors: value.author
})

Exercise #16 - Transform Object Fields

DataWeave Playground

Input
{
  "products": [
    {"id": 1, "name": "Laptop", "category": "Electronics", "price": 1200},
    {"id": 2, "name": "Shirt", "category": "Apparel", "price": 25},
    {"id": 3, "name": "Headphones", "category": "Electronics", "price": 100}
  ],
  "discounts": {
    "Electronics": 0.1,
    "Apparel": 0.05
  }
}
Script
%dw 2.0
output application/json  
---
discountedProducts: payload.products map ((product) -> 
    (product - "price") ++ {
    discountedPrice: product.price - (product.price * payload.discounts[product.category])
    })

Exercise #17 - Convert Temperature

DataWeave Playground

Input
{
  "temperaturesInCelsius": [0, 10, 25, 30, -5]
}
Script
%dw 2.0
output application/json  
---
temperaturesInFahrenheit: payload.temperaturesInCelsius map ($ * 9/5) + 32

Exercise #18 - Add Fields to Objects

DataWeave Playground

Input
{
  "products": [
    {"id": 1, "name": "Laptop", "price": 1200},
    {"id": 2, "name": "Shirt", "price": 25},
    {"id": 3, "name": "Headphones", "price": 100}
  ],
  "discountLookup": {
    "1": 0.1,
    "2": 0.05
  }
}
Script
%dw 2.0
output application/json  
---
discountedProducts: payload.products map ($ ++ 
    discounted: $.price - $.price * payload.discountLookup[$.id as String] default $.price
)

Exercise #19 - Total Amount

DataWeave Playground

Input
{
  "orderAmounts": [120, 50, 75, 200, 100]
}
Script
%dw 2.0
output application/json  
---
totalOrderAmount: sum(payload.orderAmounts)



Exercises from Medium - Faizan Arif

Table of Exercises

Exercise #1 - Dynamic Data Transformation with Functions Exercise #2 - Enrich JSON Structure Exercise #3 - Add New Field to Each Object Exercise #4 - Sort an Array of Objects Exercise #6 - Calculate Total and Average of Grouped Payload
Exercise #7/8 - Extract Values from Specified Keys Exercise #9 - Determine the Top Value per Specific Field Exercise #10 - Find and Multiply Every Number

Exercises

Exercise #1 - Dynamic Data Transformation with Functions

DataWeave Playground

Input
{
"data": [
  { "type": "text", "content": "Hello, World!" },
  { "type": "number", "content": 42 },
  { "type": "boolean", "content": true },
  { "type": "array", "content": [1, 2, 3] },
  { "type": "object", "content": { "key": "value" } }
]
}
Script
%dw 2.0
output application/json

fun transformContent(contentType, content) =
contentType match{
  case "text" ->
    transformedContent: upper(content as String)
  case "number" ->
    transformedContent: content * 2
  case "boolean" ->
    transformedContent: !content
  case "array" ->
    transformedContent: content map ($ ++ 0) as Number
  case "object" ->
    transformedContent: content mapObject { (upper($$)): upper($) }
}
---
payload.data map ((item) -> 
(item - "content") ++ (transformContent(item."type", item.content)))

Exercise #2 - Enrich JSON Structure

DataWeave Playground

Input
{
"orders": [
  {
    "orderId": "A001",
    "customer": {
      "id": "C001",
      "name": "Amit Bannerjee",
      "address": "123 Main St"
    },
    "items": [
      { "productId": "P001", "quantity": 2 },
      { "productId": "P002", "quantity": 1 }
    ]
  },
  {
    "orderId": "A002",
    "customer": {
      "id": "C002",
      "name": "Kalyan Singh",
      "address": "456 Oak St"
    },
    "items": [
      { "productId": "P001", "quantity": 1 },
      { "productId": "P003", "quantity": 5 }
    ]
  }
],
"products": [
  { "id": "P001", "name": "Widget", "price": 9.99 },
  { "id": "P002", "name": "Gadget", "price": 14.99 },
  { "id": "P003", "name": "Doohickey", "price": 19.99 }
]
}
Script
%dw 2.0
output application/json  
---
payload.orders map ((order) -> {
orderId: order.orderId,
customer: order.customer.name,
items: order.items map (item) -> 
  item ++ ((payload.products filter ($.id contains item.productId))[0]),
total: sum(order.items map (item) -> 
  item.quantity * ((payload.products filter ($.id contains item.productId)).price[0]))
})

Exercise #3 - Add New Field to Each Object

DataWeave Playground

Input
[
{ "name": "John", "department": "Engineering" },
{ "name": "Jane", "department": "Marketing" },
{ "name": "Doe", "department": "HR" }
]
Script
%dw 2.0
output application/json
---
payload map ( $ ++ ($.department match {
  case "Engineering" -> {status: "Active"}
  case "Marketing" -> {status: "Pending"}
  case "HR" -> {status: "Inactive"}
}))

Exercise #4 - Sort an Array of Objects

DataWeave Playground

Input
[
{ "task": "Task 1", "priority": "Medium" },
{ "task": "Task 2", "priority": "High" },
{ "task": "Task 3", "priority": "Low" },
{ "task": "Task 4", "priority": "High" },
{ "task": "Task 5", "priority": "Medium" }
]
Script
%dw 2.0
output application/json

fun priorityLevel(priority) = priority match {
  case "High" -> 1
  case "Medium" -> 2
  case "Low" -> 3
}
---
// Alternative: payload orderBy $.priority[-1 to 0]

payload orderBy priorityLevel($.priority)

Exercise #6 - Calculate Total and Average of Grouped Payload

DataWeave Playground

Input
[
{
    "product": "Laptop",
    "region": "North",
    "sales": [
        {
            "month": "January",
            "amount": 1200
        },
        {
            "month": "Febraury",
            "amount": 1500
        },
        {
            "month": "March",
            "amount": 1800
        }
    ]
},
{
    "product": "smartphone",
    "region": "North",
    "sales": [
        {
            "month": "January",
            "amount": 800
        },
        {
            "month": "Febraury",
            "amount": 1000
        },
        {
            "month": "March",
            "amount": 1200
        }
    ]
},
{
    "product": "Laptop",
    "region": "South",
    "sales": [
        {
            "month": "January",
            "amount": 1000
        },
        {
            "month": "Febraury",
            "amount": 1900
        },
        {
            "month": "March",
            "amount": 1500
        }
    ]
},
{
    "product": "smartphone",
    "region": "South",
    "sales": [
        {
            "month": "January",
            "amount": 1000
        },
        {
            "month": "Febraury",
            "amount": 1200
        },
        {
            "month": "March",
            "amount": 800
        }
    ]
}
]
Script
%dw 2.0
output application/json  
---
payload groupBy $.region pluck {
region: $$,
totalsales: sum($.sales map sum($.amount)),
products: $.product map ((product) -> do {
    var filteredProduct = $ filter ($.product == product)
    ---
      (product): {
        totalsales: (filteredProduct.sales map sum($.amount))[0],
        averagesales: (filteredProduct.sales map round(avg($.amount)))[0]
      }
  }) reduce ((item, acc = {}) -> acc ++ item)
}

Exercise #7/8- Extract Values from Specified Keys

DataWeave Playground

Input
{
"name1": "Root",
"children": [
  {
    "name2": "Child1",
    "children": [
      {
        "name3": "Grandchild1",
        "children": []
      },
      {
        "name4": "Grandchild2",
        "children": [
          {
            "name5": "GreatGrandchild1",
            "children": []
          }
        ]
      }
    ]
  },
  {
    "name6": "Child2",
    "children": []
  }
]
}
Script
%dw 2.0
output application/json  

fun getValues(value) =
flatten(value match {
  case is String -> []
  case is Array -> value map getValues($)
  case is Object -> value pluck ((value, key) -> 
      if (key startsWith "name")
          value
      else
          getValues(value))
})
---
flatten(getValues(payload))

Exercise #9 - Determine the Top Value per Specific Field

DataWeave Playground

Input
{
"students": [
  {
    "name": "John",
    "courses": [
      {
        "name": "Math",
        "grade": 95
      },
      {
        "name": "Science",
        "grade": 82
      },
      {
        "name": "History",
        "grade": 90
      }
    ]
  },
  {
    "name": "Alice",
    "courses": [
      {
        "name": "Math",
        "grade": 88
      },
      {
        "name": "Science",
        "grade": 95
      },
      {
        "name": "History",
        "grade": 92
      }
    ]
  },
  {
    "name": "Bob",
    "courses": [
      {
        "name": "Math",
        "grade": 75
      },
      {
        "name": "Science",
        "grade": 80
      },
      {
        "name": "History",
        "grade": 85
      }
    ]
  }
]
}
Script
%dw 2.0
output application/json  
---
payload.students flatMap ((student) -> student.courses map ((course) -> {
  "course": course.name,
  TopPerformingstudents: [
    {
      "name": student.name,
      "grade": course.grade
    }
  ]
})) groupBy ((course) -> course.course) mapObject ((value, key, index) -> value maxBy ((item) -> item.TopPerformingstudents.grade[0]))

Exercise #10 - Find and Multiply Every Number

DataWeave Playground

Input
[
2,
4,
"hello",
[5, { "name1": 10, "name2": "10" }, [9, 10, "dw", [12, [15, 17, "18", [19]]]]]
]
Script
%dw 2.0
import * from dw::util::Tree
output application/json  
---
payload mapLeafValues ((value) -> 
if (value is Number)
  value * 10
else
  value)

About

Dataweave practical exercises

Topics

Resources

Stars

Watchers

Forks