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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Streamlining Event Data in Event-Driven Ansible
  • Dynamic Web Forms In React For Enterprise Platforms
  • Unlocking Oracle 23 AI's JSON Relational Duality
  • Loading XML into MongoDB

Trending

  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • Automating Data Pipelines: Generating PySpark and SQL Jobs With LLMs in Cloudera
  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.

By 
Surya Veer user avatar
Surya Veer
·
Aug. 01, 18 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
17.1K 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

  • Streamlining Event Data in Event-Driven Ansible
  • Dynamic Web Forms In React For Enterprise Platforms
  • Unlocking Oracle 23 AI's JSON Relational Duality
  • Loading XML into MongoDB

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • 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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!