MuleSoft DataWeave: Reading From the File
Follow along with this brief tutorial to follow an example of how to read data from files using MuleSoft DataWeave.
Join the DZone community and get the full member experience.
Join For FreeBefore we start, let's go over the following:
- readurl (): It is dw-core-function and returns parsed content from source at given classpath-based url. readurl("classpath-based url","contentType").
- dynamic selector[()]: Return the value of expression passed in parentheses of dynamic selector [()].
Example of Reading Data From Files
The file in use here is zipcode.json, which has zip codes for different cities in India. It is available at classpath "/src/main/resources/".
Example 1:
Reading data from a file can be achieved by using readUrl() in DataWeave.
Data in the "zipcode.json" file is as follows:
{
"Indore" : "455001" ,
"Pune" : "411002",
"Bhopal" : "462003",
"Banglore" : "56004"
}
DataWeave Code, to cath parsed value in dwl variable and map it to a field:
%dw 2.0
output application/json
var zipcodes = readUrl("classpath://zipcode.json" , "application/json")
---
{
"usingVar" : zipcodes,
"directlyUsingURL" : readUrl("classpath://zipcode.json" , "application/json")
}
Output:
{
"usingVar": {
"Indore": "455001",
"Pune": "411002",
"Bhopal": "462003",
"Banglore": "56004"
},
"directlyUsingURL": {
"Indore": "455001",
"Pune": "411002",
"Bhopal": "462003",
"Banglore": "56004"
}
}
Example 2:
Mapping a field in response from parsed data of the file can be achieved in a single transform node using "readUrl()" and "dynamic selector [()] for single value".
Data in the "zipcode.json" file:
{
"Indore" : "455001" ,
"Pune" : "411002",
"Bhopal" : "462003",
"Banglore" : "56004"
}
Input payload:
[
{
"city": "Indore"
},
{
"city": "Bhopal"
}
]
DataWeave code:
%dw 2.0
output application/json
var zipcodes = readUrl("classpath://zipcode.json" , "application/json")
---
payload map ((item, index) -> {
"City": item.city,
"Zipcode": zipcodes[item.city]
})
Output:
[
{
"City": "Indore",
"Zipcode": "455001"
},
{
"City": "Bhopal",
"Zipcode": "462003"
}
]
Thanks!
Opinions expressed by DZone contributors are their own.
Comments