[英]Convert Delimiter fille to JSON format using Dataweave in Mule
我需要在 mule 中使用 dataweave 將現有的分隔符文件轉換為 json 格式。
樣本輸入:
Name~#~ID~#~Company~#~Address
SRI~#~1~#~Infy~#~Bangalore
Rahul~#~2~#IBM~#~US
John~#~3~#~SF~#~UK
樣品輸出
{
Name: Sri
ID: 1
Company: Infy
Adress: Bangalore
},
{
Name: Rahul
ID: 2
Company: IBM
Adress: US
},
{
Name: John
ID: 3
Company: SF
Adress: UK
}
但我低於輸出
數據編織轉換
非常有趣的問題,您可以使用dw::core::Binaries
readLines
函數,然后按~#~
拆分。 請記住將您的有效負載設置為application/octet-stream
mimeType,以便 dw 將其作為二進制數據處理,稍后您可以使用此代碼段來解析它。
%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
} )
})
}
}
使用以下輸入(input.txt):
Name~#~ID~#~Company~#~Address
SRI~#~1~#~Infy~#~Bangalore
Rahul~#~2~#~IBM~#~US
John~#~3~#~SF~#~UK
以及以下 DataWeave 代碼:
%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[$$]): $
})}
結果是:
[
{
"Name": "SRI",
"ID": "1",
"Company": "Infy",
"Address": "Bangalore"
},
{
"Name": "Rahul",
"ID": "2",
"Company": "IBM",
"Address": "US"
},
{
"Name": "John",
"ID": "3",
"Company": "SF",
"Address": "UK"
}
]
我推薦一個數組作為輸出
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.