Any better way to convert from YAML or JSON into a properties file (flatten object) using DataWeave?

84 views Asked by At

I was able to produce this script that takes a YAML or JSON file and produce a properties file. I was looking if there is any optimization or pre-built function that make code smaller if exists. I made it not support arrays on purpose.

%dw 2.0
import * from dw::util::Tree
output text/plain

fun collectLeaves(data) =  if((data is Object) == false) data else
data mapObject ((value, key, index) -> 
    value match {
        case value is Object -> collectLeaves(value)
        else -> (key) : value
    }
)

fun objToProperties(obj) = 
    (obj pluck ((value, key, index) -> 
        "$(key)=$(value)"
    )) joinBy "\n"

var aggregatedKeys = payload mapLeafValues (value, path) -> { (joinBy(path.selector,".")): value }

var propertiesObject = collectLeaves(aggregatedKeys)

---
objToProperties(propertiesObject)

Example input:

db:
  host: "db.example.com"
  port: "1234"
  pass: "pass123"
  config:
    pool: "3"
log:
  level: "INFO"

Example output:

db.host=db.example.com
db.port=1234
db.pass=pass123
db.config.pool=3
log.level=INFO
0

There are 0 answers