read function is used to read the string or binary and returned parsed content. It is a very useful function when the reader isn’t able to determine the content type by default.
read(stringToParse: String | Binary, contentType: String = "application/dw", readerProperties: Object = {}): Any
Name | Description |
---|---|
stringToParse | The string or binary to read. |
contentType | A supported format (or content type). Default: application/dw . |
readerProperties | Optional: Sets reader configuration properties. For other formats and reader configuration properties, see Supported Data Formats. |
In this example, inputData
is in string format and using the read
function, we can parse into CSV format.
Source
%dw 2.0
output application/json
var inputData=
"name,age,salary
Joseph,34,3000
James,32,5000"
---
read(inputData,"application/csv")
Output
[
{
"name": "Joseph",
"age": "34",
"salary": "3000"
},
{
"name": "James",
"age": "32",
"salary": "5000"
}
]
This example reads a string as a CSV format without a header and transforms it to JSON.
Source
%dw 2.0
var myVar = "Some, Body"
output application/json
---
read(myVar,"application/csv",{header:false})[0]
Output
{
"column_0": "Some",
"column_1": " Body"
}
This example reads a JSON object { "hello" : "world" }'
, and it uses the "application/json"
argument to indicate input content type. By contrast, the output application/xml
directive in the header of the script tells the script to transform the JSON content into XML output. Notice that the XML output uses hello
as the root XML element and world
as the value of that element. The hello
in the XML corresponds to the key "hello"
in the JSON object, and world
corresponds to the JSON value "world"
.
Source
%dw 2.0
output application/xml
---
read('{ "hello" : "world" }','application/json')
Output
<?xml version='1.0' encoding='UTF-8'?>
<hello>world</hello>
If you like my post please follow me to read my latest post on programming and technology.
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…
Build an autocomplete system that, given a query string s and a set of possible…
Design a job scheduler that accepts a function f and an integer n. The scheduler…