Last active
December 7, 2024 11:19
-
-
Save AndyDaSilva52/698fdaf5435d0745eb1a57a5fcf102f0 to your computer and use it in GitHub Desktop.
DataWeave - Transform XML into JSON forcing Keys to Always return as Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%dw 2.0 | |
output application/json duplicateKeyAsArray = true | |
// | |
var payload = read('<?xml version="1.0" encoding="UTF-8"?><Root><About><Code>29329573000145</Code><Name>COMPANY X</Name><CodeStatus>Ativa</CodeStatus></About><Emails><Email>[email protected]</Email></Emails><Emails><Email>[email protected]</Email></Emails><Phones><AreaCode>19</AreaCode><Phone>34140000</Phone></Phones><Phones><AreaCode>19</AreaCode><Phone>34370005</Phone></Phones><Mobiles><AreaCode>11</AreaCode><Phone>912341234</Phone></Mobiles><Mobiles><AreaCode>11</AreaCode><Phone>956785678</Phone></Mobiles></Root>', 'application/xml') | |
var root = 'Root' | |
var arrayKeys = ["Emails", "Phones", "Mobiles"] | |
var objectKeys = keysOf( (payload.'$(root)' default {}) as Object) -- (arrayKeys) | |
--- | |
{ | |
(objectKeys map { | |
(($): ((payload.'$(root)'.'$($)' default {}) as Object mapObject ((value, key, index) -> | |
(key): (value match { | |
case is String -> ( | |
if(trim(value) ~= "NULL") null else trim(value) | |
) | |
else -> value | |
}) | |
))) | |
}), | |
( | |
arrayKeys map { | |
( | |
($): ( | |
(payload.'$(root)'.*'$($)' default []) as Array map ((item, index) -> | |
item as Object mapObject ((value, key, index) -> | |
(key): (value match { | |
case is String -> ( | |
if(trim(value) ~= "NULL") null else trim(value) | |
) | |
else -> value | |
}) | |
) | |
) | |
) | |
) if(payload.'$(root)'.'$($)'?) | |
}) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment