CSV to JSON Conversion in Mule 4

CSV to JSON in Mule 4


We can use dataweave transformation to transform data from csv file into json format.

flow of csv to json transformation : 

 
File structure:

 


new.csv:

empid,name
1,Rahul
2,Rohit

File.json

[{
"id":2,
"name":"Himanshu"
}]


Transform Message settings:

 

Method: GET

Output:
[
  {
    "id": 1,
    "name": "Rahul"
  },
  {
    "id": 2,
    "name": "Rohit"
  }
]


XML Project code:

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:file="http://www.mulesoft.org/schema/mule/file" xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core"
       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:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="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/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd">
       <http:listener-config name="HTTP_Listener_config" doc:name="HTTP Listener config" doc:id="d71ebfb4-29de-4b40-a68c-894ea43753cb" >
              <http:listener-connection host="0.0.0.0" port="8085" />
       </http:listener-config>
       <file:config name="File_Config" doc:name="File Config" doc:id="5d903a69-59d7-45e5-9ced-377701de8f66" >
              <file:connection workingDir="C:\AnypointStudio\studio-workspace\test_csvtojson\src\main\resources" />
       </file:config>
       <flow name="test_csvtojsonFlow" doc:id="0748bbb1-6b8b-41fc-bf4d-68421cc8114c" >
              <http:listener doc:name="Listener" doc:id="f8befbea-1db9-4fee-b579-5c85601a0034" config-ref="HTTP_Listener_config" path="/csvtojson"/>
              <file:read doc:name="Read" doc:id="499da6ab-eb90-4389-9a8b-3ffe9ea02a0e" config-ref="File_Config" path="C:\AnypointStudio\studio-workspace\test_csvtojson\src\main\resources\new.csv"/>
              <ee:transform doc:name="Transform Message" doc:id="f520f96a-a4ac-4253-ab7b-0e87b91bb689" >
                     <ee:message >
                           <ee:set-payload ><![CDATA[%dw 2.0
input payload application/csv
output application/json
---
payload map ( payload01 , indexOfPayload01 ) -> {
       id: payload01.empid as Number,
       name: payload01.name
}]]></ee:set-payload>
                     </ee:message>
              </ee:transform>
              <logger level="INFO" doc:name="Logger" doc:id="343ae37b-5177-4bd8-9190-a30739b5357f" message="#[payload]"/>
       </flow>
</mule>