Hassan Raza
Hassan Raza

Reputation: 116

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

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

Upvotes: 1

Views: 821

Answers (2)

aled
aled

Reputation: 25709

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

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

Upvotes: 3

Jorge Garcia
Jorge Garcia

Reputation: 1383

One alternative is using the pluck function. It lets you iterate over an object receiving the entries.

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

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

Upvotes: 1

Related Questions