2
votes

I need to convert existing delimiter file to json format using dataweave in mule.

Sample Input:

Name~#~ID~#~Company~#~Address
SRI~#~1~#~Infy~#~Bangalore
Rahul~#~2~#IBM~#~US
John~#~3~#~SF~#~UK

Sample outPut

{
Name: Sri
ID: 1
Company: Infy
Adress: Bangalore
},
{
Name: Rahul
ID: 2
Company: IBM
Adress: US

},
{
Name: John
ID: 3
Company: SF
Adress: UK
}

But i am getting below output

Output

Dataweave Transforamtion

Dataweave Transforamtion

2
Why do you ask the same question twice? stackoverflow.com/questions/64347572/…Christian Baumann
Is it valid to have a separator with multiple characters?George

2 Answers

5
votes

Very interesting question you can use readLines function from dw::core::Binaries and then split by ~#~. Remember to set your payload to application/octet-stream mimeType so dw will handle this as a Binary data and later you can use this snippet to parse it.

%dw 2.0
output application/json
import dw::core::Binaries
var lines = Binaries::readLinesWith(payload, "UTF-8")


---
lines match {
    case [x ~ xs] -> do {
        var header = x splitBy  "~#~"
        ---
        xs map ((item, index) -> {
              (item splitBy "~#~" map (column, index) -> {
                  (header[index]): column
              } )
        })
    }
}
4
votes

With the following input (input.txt):

Name~#~ID~#~Company~#~Address
SRI~#~1~#~Infy~#~Bangalore
Rahul~#~2~#~IBM~#~US
John~#~3~#~SF~#~UK

And the following DataWeave code:

%dw 2.0
output application/json

var payload = readUrl("classpath://input.txt","text/plain") splitBy(/\r\n/)

var header= payload[0] splitBy(/~#~/)
var data  = payload[1 to -1]
---
data map (item, index) ->
    {(item splitBy(/~#~/) map
    {   
        (header[$$]): $ 
    })}

The result is:

[
  {
    "Name": "SRI",
    "ID": "1",
    "Company": "Infy",
    "Address": "Bangalore"
  },
  {
    "Name": "Rahul",
    "ID": "2",
    "Company": "IBM",
    "Address": "US"
  },
  {
    "Name": "John",
    "ID": "3",
    "Company": "SF",
    "Address": "UK"
  }
]

I recommend an array as an output