Recently, I was posed with an interesting challenge; transform this array of key/value pairs:

[
   {
      "key":"Key1",
      "value": "Value1"
   },
   {
      "key":"Key2",
      "value": "Value2"
   }
]

… into this object:

{
   "Key1": "Value1",
   "Key2": "Value2"
}

 

On the face of it, this should be easy. And yet… I struggled, for some reason. All of the usual suspects failed me. I tried countless variations of the following built-in functions:

  • Map()
  • MapObject()
  • Flatten()

… and then some. For some reason, no combination of function calls I could think of was able to produce the result I needed.

It began to feel as if I was asking more of the Mule than it was able to bear. However, I refused to give up.

I whispered…

And the Mule delivered!

In the absence of an elegant Dataweave script, I guess an inelegant one will have to do. So I produced the following script:

%dw 2.0
output application/json
---
read("{" ++ ((payload map(item,index)->(item.key ++ ":'" ++ item.value ++ "'")) joinBy ",") ++ "}")

 

I am the first to admit that this script looks a little clunky. However, it works perfectly and produces the correct output for the use-case.

That said, a part of me still felt that I had missed something. In my gut I knew that there was a more elegant solution that continued to elude me.

After ruminating on the problem for a few days I whispered again…

And, once again, the Mule Delivered!

%dw 2.0
output application/json
---
(payload map(item,index)->{(item.key): (item.value)}) reduce ($$ ++ $)

This is just…

well — sexier!

First, it is thirty characters shorter. Second and more importantly it doesn’t waste precious CPU time with silly conversions from Object to String and then back again. It also avoids all of the complex String manipulation in the previous solution. Instead, it uses two common Dataweave functions:

  • map() and
  • reduce()

… that countless Muleys out there already know and love.

Feeling much better about the solution in its new form.

My Take-away from this experience? A Mule Whisperer’s journey is never done; rather, it is an ongoing search for perfection.