0
votes

I have a simple json payload having key and value in it. I want to transform it into 'key1=value1','key2=value2' just like this.

For example i have a json:

{
"name":"xyz",
"age" :"##",
"contact":"##########"
}

I want to transform it into format 'name=xyz','age=##','contact=##########'.

I have also written a small code, which is not working for me and it is throwing error "cannot coerce Array into object".

Code1:

***%dw 2.0
output application/json
---
(payload mapObject(value,key)->{
    (key):(key) ++ "=" ++ " '" ++ value ++ "'"
}pluck(value,key)->{(key):(value)})***

Code1 Out: (error)"cannot coerce Array into object"

but for the same purpose if i write the below code2 then it is working fine for me.

Code2:

***%dw 2.0
output application/json
---
(payload mapObject{
     ($$): (($$) ++ "=" ++ "'" ++ ($) ++ "'")
} pluck ($) joinBy " , ")***

Code2 Output: 'name=xyz','age=##','contact=##########'

But I want to know why Code 1 is giving error for the same, and how to solve this.

1

1 Answers

0
votes

You got it almost right. The only issue - a little weird Mule's order of operator evaluation. It does not always match what you think it is. Easy fix - provide clear order with parenthesis.

%dw 2.0
var x={
"name":"xyz",
"age" :"##",
"contact":"##########"
}
output application/java
---
"'" ++
(
  ( x mapObject(value,key)->(
      (key):(key) ++ "'='" ++ value ++ "'"
    )
  ) pluck ( $ ) joinBy ",'"
)

enter image description here Here is another example how you can transform array to string https://simpleflatservice.com/mule4/ArrayAsStringViaJava.html However it uses Java quotation with double quotes and not single quotes.