Contact Free trial Login

Format According to Type

This DataWeave example applies changes to the keys in an object, depending on the type of their corresponding values. When the element is an array, the keys are pluralized. When it’s a number, they are set to camel case. In any other case they are capitalized.

Before you begin, note that DataWeave 2.0 (%dw 2.0) is for Mule 4 apps. For a Mule 3 app, refer to DataWeave 1.0 (%dw 1.0) examples, within the Mule 3.9 documentation set. For other Mule versions, you can use the Mule Runtime version selector in the table of contents.

The example uses:

  • mapObject to go through each element in the payload.

  • if to check that an element is of a given type.

  • camelize from the String library to apply a camel case format to strings (all words stringed together, using upper case letters to mark separations).

  • capitalize from the String library to apply a capitalized format to strings (all words are separate and start with an upper case letter).

  • pluralize from the String library to change singular words into plural.

DataWeave Script:
%dw 2.0
import * from dw::core::Strings
output application/json
---
payload mapObject ((elementValue, elementKey) -> {
  (if (elementValue is Array)
      pluralize(elementKey)
    else if(elementValue is Number)
      camelize(elementKey)
    else capitalize(elementKey)) : elementValue
})
Input JSON Payload:
{
  "VersionNo": 1.6,
  "StoreOfOrigin": "SFO",
  "Item":
    [
      {
        "ID":"34546315801",
        "DeliveryMethod":"AIR",
        "Quantity":8
      },
      {
        "ID":"56722087289",
        "Boxes": 3,
        "DeliveryMethod":"GROUND",
        "Quantity":2
      }
    ]
  }
Output JSON:
{
  "versionNo": 1.6,
  "Store Of Origin": "SFO",
  "Items": [
    {
      "ID": "34546315801",
      "DeliveryMethod": "AIR",
      "Quantity": 8
    },
    {
      "ID": "56722087289",
      "Boxes": 3,
      "DeliveryMethod": "GROUND",
      "Quantity": 2
    }
  ]
}

Was this article helpful?

💙 Thanks for your feedback!

Edit on GitHub