Categories: Dataweave

read function in 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

Recent Posts

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

20 hours ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

3 weeks ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

1 month ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

1 month ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

2 months ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

2 months ago