-1

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?

aled
  • 21,330
  • 3
  • 27
  • 34
Gorodeckij Dimitrij
  • 4,209
  • 2
  • 17
  • 21

1 Answers1

1

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($$)) : $ )
aled
  • 21,330
  • 3
  • 27
  • 34
  • well I am not expert that's why asking a better way :) I like your approach and realy appreciated for your help. In that function if where is no town key present (or district) will it run without errors? – Gorodeckij Dimitrij Dec 09 '21 at 08:54
  • 1
    Yes, it is the same as processing one of the other keys, like owner. mapObject works independently for each key. – aled Dec 09 '21 at 10:18