简体   繁体   中英

String Map to Object / JSON - Mule DataWeave

I have a string like this (which looks like a map)

{key1=value1;key2=value2;key3=value3;...keyn=valuen;}

which I want to either convert to a java object or as a JSON payload like this:

{"key1" : "value1","key2" : "value2","key3" : "value3",..."keyn" : "valuen"}

Is there a mule way to do it ? I am trying to avoid writing a custom java class for this problem. Something which data weave can help?

I have used following in dataweave to manipulate string.

%dw 1.0
%output application/json
---
(payload replace /[{}]/ with "" splitBy ";")  map using (data = $ splitBy "=")   {
    (data[0]) : data[1]
}

Input data :-

"{key1=value1;key2=value2;key3=value3;keyn=valuen}"

Output :-

[
  {
    "key1": "value1"
  },
  {
    "key2": "value2"
  },
  {
    "key3": "value3"
  },
  {
    "keyn": "valuen"
  }
]

Hope this helps..

Use this to get map

%dw 1.0
%output application/json
---
{((payload replace /[{}]/ with "" splitBy ";")  map using (data = $ splitBy "="){
    (data[0]) : data[1]
})}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM