Map Object Elements as an Array

This DataWeave example uses the DataWeave map function to iterate through the object elements that match the key book. The input also includes the key magazine, which is ignored. Before you begin, note that 2.x versions of DataWeave are used by Mule 4 apps. For DataWeave in Mule 3 apps, refer to DataWeave version 1.2 examples. For other DataWeave versions, you can use the version selector in the DataWeave table of contents.

The example uses these DataWeave functions:

  • The multi-value selector *book to return an array with the elements that match the key "book".

  • map to go through each object in the array that’s returned by the multi-value selector.

DataWeave Script:
%dw 2.0
var myInputExample = {
  "inventory": {
      "book" : {
        "category": "cooking",
        "title": "Everyday Italian",
        "author": "Giada De Laurentiis",
        "year": "2005",
        "price": "30.00"
      },
      "book" :{
        "category": "children",
        "title": "Harry Potter",
        "author": "J K. Rowling",
        "year": "2005",
        "price": "29.99"
      },
      "book" :{
        "category": "web",
        "title": "Learning XML",
        "author": "Erik T. Ray",
        "year": "2003",
        "price": "39.95"
      },
      "magazine" :{
        "category": "web",
        "title": "Wired Magazine",
        "edition": "03-2017",
        "price": "15.95"
      },
        "magazine" :{
        "category": "business",
        "title": "Time Magazine",
        "edition": "04-2017",
        "price": "17.95"
      }
   }
}
output application/json
---
items: myInputExample.inventory.*book map (item, index) -> {
      "theType": "book",
      "theID": index,
      "theCategory": item.category,
      "theTitle": item.title,
      "theAuthor": item.author,
      "theYear": item.year,
      "thePrice": item.price as Number
}
Output JSON:
{
  "items": [
    {
      "theType": "book",
      "theID": 0,
      "theCategory": "cooking",
      "theTitle": "Everyday Italian",
      "theAuthor": "Giada De Laurentiis",
      "theYear": "2005",
      "thePrice": 30.00
    },
    {
      "theType": "book",
      "theID": 1,
      "theCategory": "children",
      "theTitle": "Harry Potter",
      "theAuthor": "J K. Rowling",
      "theYear": "2005",
      "thePrice": 29.99
    },
    {
      "theType": "book",
      "theID": 2,
      "theCategory": "web",
      "theTitle": "Learning XML",
      "theAuthor": "Erik T. Ray",
      "theYear": "2003",
      "thePrice": 39.95
    }
  ]
}

Was this article helpful?

💙 Thanks for your feedback!

Edit on GitHub