Contact Us 1-800-596-4880

Dynamically Map Based on a Definition

You can create a transformation that can dynamically change what it does depending on a definition input. This DataWeave example receives both a payload input, and a variable named mappings that specifies how to rename each field and what default value to use in each. 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 the following:

  • A map function to go through all of the elements in the input array. Also a second map function to go through each field in each element.

  • A custom function that applies the changes specified in the mappings variable.

  • default to set a default value, that comes from the mappings variable.

DataWeave Script:
%dw 2.0
output application/json
var applyMapping = (in, mappingsDef) -> (
   mappingsDef map (def) -> {
    (def.target) : in[def.source] default def."default"
  }
)
---
payload.sfdc_users.*sfdc_user map (user) -> (
        applyMapping(user, vars.mappings)
)
Input XML Payload:
<sfdc_users>
    <sfdc_user>
      <sfdc_name>Mariano</sfdc_name>
      <sfdc_last_name>Achaval</sfdc_last_name>
      <sfdc_employee>true</sfdc_employee>
    </sfdc_user>
    <sfdc_user>
      <sfdc_name>Julian</sfdc_name>
      <sfdc_last_name>Esevich</sfdc_last_name>
      <sfdc_employee>true</sfdc_employee>
    </sfdc_user>
    <sfdc_user>
      <sfdc_name>Leandro</sfdc_name>
      <sfdc_last_name>Shokida</sfdc_last_name>
    </sfdc_user>
</sfdc_users>
Input JSON Mule Event Variable (vars.mappings):
[
  {
    "source": "sfdc_name",
    "target": "name",
    "default": "---"
  },
  {
    "source": "sfdc_last_name",
    "target": "lastName",
    "default": "---"
  },
  {
    "source": "sfdc_employee",
    "target": "user",
    "default": true
  }
]
Output JSON:
[
  [
    {"name": "Mariano"},
    {"lastName": "Achaval"},
    {"user": "true"}
  ],
  [
    {"name": "Julian"},
    {"lastName": "Esevich"},
    {"user": "true"}
  ],
  [
    {"name": "Leandro"},
    {"lastName": "Shokida"},
    {"user": true}
  ]
]