DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Containers Trend Report: Explore the current state of containers, containerization strategies, and modernizing architecture.

Low-Code Development: Learn the concepts of low code, features + use cases for professional devs, and the low-code implementation process.

E-Commerce Development Essentials: Considering starting or working on an e-commerce business? Learn how to create a backend that scales.

Related

  • Accelerating Insights With Couchbase Columnar
  • A Comprehensive Guide To Working With JSON in JavaScript
  • How I Used Swift Script in Electron Browser Natively
  • Migrating MuleSoft System API to AWS Lambda (Part 1)

Trending

  • A Guide to Missing Sprint Goals
  • CodeCraft: Agile Strategies for Crafting Exemplary Software
  • Enhancing Observability With AI/ML
  • Apply Strangler Pattern To Decompose Legacy System Into Microservices: Part 1
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. JSON to JSON Conversion Using Dataweave and Datamapper

JSON to JSON Conversion Using Dataweave and Datamapper

Want to know how to transform one kind of JSON to another kind of JSON? Let's take a look at this article's explanation on how to do that.

Surya Veer user avatar by
Surya Veer
·
Aug. 01, 18 · Tutorial
Like (3)
Save
Tweet
Share
16.2K Views

Join the DZone community and get the full member experience.

Join For Free

Sometimes, converting an incoming payload to JSON using XML to JSON or Object to JSON does not give us the required output. Here, I am going to explain a step-by-step method of transforming one kind of JSON to another kind of JSON.

If you are using Mule Runtime 3.8 or above, you can do that using Dataweave, and if you are using 3.6x or below, you can use Datamapper.   

First, let's see the requirements we have:

Incoming JSON

{
  "name": {
 "firstName": "John",
   "lastName": "Doe"
  },
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York"
  },
  "phoneNumber": [
    {
      "phoneNumber": 6788989,
      "areaCode": 647
    },{
      "phoneNumber": 6788990,
      "areaCode": 647
      }
  ],
"otherInformation":{
  "gender":"M",
  "dateOfBirth":"19-11-1970"
   }
}

Desired JSON:

{
   "firstName": "John",
   "lastName": "Doe",
   "street": "21 2nd Street",
   "city": "New York",
   "PhoneNumbers":[{"no":6476788989},{"no":647678890}],
   "gender": "M",
   "dateOfBirth":"19-11-1970"
}

Suppose the first JSON is the incoming request and we need to transform that JSON to the second type of JSON as shown:  

Let's do this using DATAWEAVE:

This the Configuration XML that is going to be generated when we follow the below explained steps:

<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:metadata="http://www.mulesoft.org/schema/mule/metadata" xmlns:dw="http://www.mulesoft.org/schema/mule/ee/dw" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd">
    <http:listener-config name="HTTP_Listener_Configuration4" host="0.0.0.0" port="9098" doc:name="HTTP Listener Configuration"/>
    <flow name="dataweave_exampleFlow">
        <http:listener config-ref="HTTP_Listener_Configuration4" path="/dataweave" doc:name="HTTP"/>
        <byte-array-to-string-transformer doc:name="Byte Array to String"/>
        <logger message="----------------------BEfore-------------- &gt;#[payload]" level="INFO" doc:name="Logger"/>
        <dw:transform-message doc:name="Transform Message" metadata:id="cfc4ea47-dd3a-401f-b21e-a70dfbe78b07">
            <dw:input-payload doc:sample="\\rsavdifs\ROOT\Homes\joh6666\Desktop\inputJSON.json" mimeType="application/json"/>
            <dw:set-payload><![CDATA[%dw 1.0
%output application/json
---
{
firstName: payload.name.firstName,
lastName: payload.name.lastName,
street: payload.address.streetAddress,
city: payload.address.city,
PhoneNumbers: payload.phoneNumber map ((phoneNumber , indexOfPhoneNumber) -> {
no: phoneNumber.areaCode ++ "" ++ phoneNumber.phoneNumber  
}),
gender: payload.otherInformation.gender,
dateOfBirth: payload.otherInformation.dateOfBirth
}]]></dw:set-payload>
        </dw:transform-message>
        <logger message="#[payload]" level="INFO" doc:name="Logger"/>
    </flow>
</mule>

Now lets see all this step by step:

1. Drag and drop the HTTP component, Configure it. (Simple you can do that)

2. Drag and drop Byte Array to string so that we can log our incoming request. (Human Readable)

3. Log the incoming request.

4. Now drag and drop the "Transform Message" or "dataWeave" and configure it as shown below.

i. First Save both the JSON in your local with .json extension. 

ii.Now in Transform message click on "DEFINE METADATA"(highlighted) for input ->Add -> Choose JSON->Example->your incoming request(that you have saved).

iii. repeat this for output metadata with the desirable JSON.

Image title

Image title

iv. When you do these steps mapping will be automatically generated and you can check the desirable output using "preview" section as shown in below image.

Image title

v. Since I needed to concatenate areaCode and PhoneNumber, I needed to change the mapping a little bit, that you can see when you will do this practically.

5. Add the logger and log the response payload and deploy the program, you will get the desired output.

JSON DataMapper

Opinions expressed by DZone contributors are their own.

Related

  • Accelerating Insights With Couchbase Columnar
  • A Comprehensive Guide To Working With JSON in JavaScript
  • How I Used Swift Script in Electron Browser Natively
  • Migrating MuleSoft System API to AWS Lambda (Part 1)

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: