简体   繁体   English

在 Dataweave 2.0 中将属性从属性文件转换为 json

[英]Convert properties from properties file into json in Dataweave 2.0

How to convert properties from a properties file如何从属性文件转换属性

creditmaster.metadata.AverageFicoScore=700
creditmaster.a.b.c=xyz

into this json format in a generic way以通用方式进入此 json 格式

{
  creditmasterMetaData: [
     {
       attributeKey: "AverageFicoScore",
       attributeValue: 700
     }
  ]
}

This script is generic in that it doesn't matter what are the parts of the key, it only groups by the first element (before of the first dot) and the key name after the last dot, it ignores everything in the middle:这个脚本是通用的,因为它不关心键的部分是什么,它只按第一个元素(第一个点之前)和最后一个点之后的键名分组,它忽略了中间的所有内容:

%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)

Input file:输入文件:

creditmaster.metadata.AverageFicoScore= 700
other.a.b= 123
creditmaster.a.b.c=xyz
something.metadata.another.maximum=456
creditmaster.metadata.different.minimum=500

Output (in JSON for clarity): Output(为了清楚起见,在 JSON 中):

{
  "something": [
    {
      "attributeKey": "maximum",
      "attributeValue": "456"
    }
  ],
  "creditmaster": [
    {
      "attributeKey": "minimum",
      "attributeValue": "500"
    },
    {
      "attributeKey": "AverageFicoScore",
      "attributeValue": "700"
    }
  ]
}

One alternative is using the pluck function.一种替代方法是使用pluck function。 It lets you iterate over an object receiving the entries.它允许您遍历接收条目的 object。

If you have this input如果你有这个输入

{
  "creditmaster": {
    "metadata": {
      "AverageFicoScore": "700",
      "OtherData": "Some value"
    }
  }
}

with this transformation通过这种转变

{
  creditmasterMetaData:
    payload.creditmaster.metadata pluck ((value, key, index) -> 
      {
        attributeKey: key,
        attributeValue: value
      }
    )
}

you get this output你得到这个 output

{
  "creditmasterMetaData": [
    {
      "attributeKey": "AverageFicoScore",
      "attributeValue": "700"
    },
    {
      "attributeKey": "OtherData",
      "attributeValue": "Some value"
    }
  ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM