This is the first article on Dataweave series, we will explore below concepts in this article
- Dataweave Introduction
- Dataweave code Structure
- Basic example of Dataweave XML to JSON
Dataweave Introduction:
The Dataweave Language is a powerful template engine that allows you to transform data to and from any kind of format (XML, CSV, JSON, Pojos, Maps, etc).
In Anypoint Studio, this language can be used in:
a) The Transform Message Component,
b) Any Mule component that accepts Mule Expression Language, through MEL DataWeave Functions
Dataweave code Structure:
DataWeave files are divided into two main sections:
1. The Header, which defines directives (optional)
2. The Body, which describes the output structure
The two sections are delimited by a separator, which is not required if no header is present. The separator consists of three dashes: "---"
The DataWeave header contains the directives, which define high level information about your transformation. The structure of the Header is a sequence of lines, each with its own Directives. The Header is terminated with '---'.
Through directives you can define:
- DataWeave version
- Input types and sources
- Output type
- Namespaces to import into your transform
- Constants that can be referenced throughout the body
- Functions that can be called throughout the body
All directives are declared on the header section of your DataWeave document and act upon the entire scope of it.
Directives are a mechanism to declare variables and constants and namespace aliases which need to be referenced in the Document.
They are also needed to declare the type of the output of your transform.
In Anypoint Studio, you can optionally use them to declare additional inputs. You rarely need them for this as any data arriving in the incoming Mule Message is already implicitly recognized as an input.
Basic example of Dataweave XML to JSON:
Input
{
"title": "Java 8 in Action",
"author": "Mario Fusco",
"year": 2014
}
Transform:
%dw 1.0
%output application/xml
---
{
order: {
type: "Book",
title: payload.title,
details: "By $(payload.author) ($(payload.year))"
}
}
Output:
<?xml version='1.0' encoding='UTF-8'?>
<order>
<type>Book</type>
<title>Java 8 in Action</title>
<details>By Mario Fusco (2014)</details>
</order>
No comments:
Post a Comment