Mule JSON - how to transform key value pairs to a list

1.4k views Asked by At

I have a json payload with the following format:

{"key":"value",
 "key:1":"value",
 "key:2","value",
 "junk key":"value",
 "part":"value",
 "part:1","value", 
 "part:2","value"...}

and want to transform it to:

{"1":{
   "key":"value",
   "part":"value"
   },
 "2": {
   "key":"value",
   "part":"value"
   },
 "3": {
   "key":"value",
   "part":"value"
   }
}

Any thoughts?

2

There are 2 answers

1
Senthil c On

Here is the closet output I could get using Dataweave, just the formatting of removing additional curly braces could be done in the subsequent message processor using MEL or simple java code. Hope it helps!!

Input JSON {
"key":"value1", "key:1":"value2", "key:2":"value3", "junk key":"value4", "part":"value5", "part:1":"value6", "part:2":"value7" }

Dataweave Logic:

%dw 1.0
%output application/json

%var keyValues = payload mapObject {
    ('$$' : $)when ( '$$' matches /key(:\d)?/)
}
%var partValues = payload mapObject {
    ('$$' : $)when ( '$$' matches /part(:\d)?/)
}
%var zipValues = (keyValues zip partValues) map {
    '$$': {
        key: $[0],
        part: $[1]
    }
}
---
zipValues map {
    '$$' : $[0]
}

Result

[
  {
    "0": {
      "key": "value1",
      "part": "value5"
    }
  },
  {
    "1": {
      "key": "value2",
      "part": "value6"
    }
  },
  {
    "2": {
      "key": "value3",
      "part": "value7"
    }
  }
]
0
Ryan Hoegg On

Senthil has a working solution already, but here's a general solution for any keys that contain a colon:

%dw 1.0
%output application/json
%function parseKeys(o) o pluck { 
    key: $$ replace /(\w+)(:\w+)?/ with $[1],
    group: $$ match {
        /(\w+):(\w+)/ -> $[2],
        default -> null
    },
    value: $
}
%function toNiceObject(tuples) {(tuples map {($.key): $.value})}
---
parseKeys(payload)
filter ($.group != null)
groupBy $.group
mapObject (
    '$$': toNiceObject($)
)

I thought it would be best to first break up the keys (the parseKeys function), producing an array of objects that have key, group, and value fields. Then we can filter and groupBy the intermediate data structure, and turn it back into tuples for the result object at the end (toNiceObject).

The other thing to notice is the use of pluck and match to make parseKeys work. pluck takes an object and produces an array by applying the given function to each key value pair (tuple) in the object. match lets us apply different transformations to a given input based on some criteria, in this case a regular expression.