read function in DataWeave

  • February 5, 2022
  • Dataweave

read Function

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

It takes three parameters:

NameDescription
stringToParseThe string or binary to read.
contentTypeA supported format (or content type). Default: application/dw.
readerPropertiesOptional: Sets reader configuration properties. For other formats and reader configuration properties, see Supported Data Formats.

Example

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"
  }
]

Example

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"
}

Example

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>
Follow Me

If you like my post please follow me to read my latest post on programming and technology.

Instagram

Facebook

Leave a Reply

Your email address will not be published. Required fields are marked *