Search code examples
muledataweavepayloadmule-esb

how properly to add and remove elements from payload? (or replace on condition)


So I have payload that have old type of attributes, and I want to migrate them to be as new ones that all the rest logic is using. So before do validation I want modify it a bit. Currently I manage to add and remove in separate transforms, but should it be possible to do in one go?

example payload:

{
  "country": "Country",
  "town": "Town",
  "district": "Dist",
  "owner": "Owner"
}

and output should be:

{
  "country": "Country",
  "city": "Town",
  "area": "Dist",
  "owner": "Owner"
}

so I add transform:

%dw 1.0
%output application/json
---
payload ++ {city: payload.town}
when 
  payload.town != null
otherwise
  payload ++ {area: payload.distrinct}
when
  payload.distrinct != null
otherwise
  payload

I want to check if payload have no null values in town key and add new key city with town key value, and same check if distrinct is not null then add its value as area key. However its happening only for city (I know it will be added at the bottom, but order is not a problem in my case) however keys may not present (it may no town, or may no distrinct or may no both)

And on next transform:

%dw 1.0
%output application/json
---
payload -- {town: payload.town}
when 
  payload.town != null
otherwise
  payload

I try to check if keys exist then delete old ones, but no luck on such :( Any help?


Solution

  • That's too complicated. Instead of adding and removing keys you can just use mapObject to transform each key. Then it becomes trivial to parametrize the transformation. Also using default is simpler than when...otherwise when a value is null.

    %dw 1.0
    %output application/json
    %var keyMap={ town: "city", district: "area" }
    %function replaceKey(keyName) (keyMap[keyName] default keyName)
    ---
    payload mapObject  ( (replaceKey($$)) : $ )