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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago