[英]Convert properties from properties file into json in Dataweave 2.0
如何從屬性文件轉換屬性
creditmaster.metadata.AverageFicoScore=700
creditmaster.a.b.c=xyz
以通用方式進入此 json 格式
{
creditmasterMetaData: [
{
attributeKey: "AverageFicoScore",
attributeValue: 700
}
]
}
這個腳本是通用的,因為它不關心鍵的部分是什么,它只按第一個元素(第一個點之前)和最后一個點之后的鍵名分組,它忽略了中間的所有內容:
%dw 2.3
output application/java
import * from dw::core::Strings
fun mapProperties(props) =
entriesOf(props) // since Mule 4.3 / DW 2.3
filter (substringAfter($.key, ".") startsWith "metadata.") // to filter keys with .metadata.
groupBy ((item, index) -> substringBefore(item.key, "."))
mapObject ((value, key, index) ->
(key): value map {
attributeKey: substringAfterLast($.key, "."),
attributeValue: if (isInteger($.value)) $.value as Number else $.value
}
)
---
mapProperties(payload)
輸入文件:
creditmaster.metadata.AverageFicoScore= 700
other.a.b= 123
creditmaster.a.b.c=xyz
something.metadata.another.maximum=456
creditmaster.metadata.different.minimum=500
Output(為了清楚起見,在 JSON 中):
{
"something": [
{
"attributeKey": "maximum",
"attributeValue": "456"
}
],
"creditmaster": [
{
"attributeKey": "minimum",
"attributeValue": "500"
},
{
"attributeKey": "AverageFicoScore",
"attributeValue": "700"
}
]
}
一種替代方法是使用pluck
function。 它允許您遍歷接收條目的 object。
如果你有這個輸入
{
"creditmaster": {
"metadata": {
"AverageFicoScore": "700",
"OtherData": "Some value"
}
}
}
通過這種轉變
{
creditmasterMetaData:
payload.creditmaster.metadata pluck ((value, key, index) ->
{
attributeKey: key,
attributeValue: value
}
)
}
你得到這個 output
{
"creditmasterMetaData": [
{
"attributeKey": "AverageFicoScore",
"attributeValue": "700"
},
{
"attributeKey": "OtherData",
"attributeValue": "Some value"
}
]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.