Last active
January 6, 2021 16:47
-
-
Save mikeacjones/1c01721df3ca4558d76643a9401ab8dd to your computer and use it in GitHub Desktop.
Function to convert XML to JSON, while expanding attribute if there are any
This file contains 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 | |
var expandXmlAttrs = (payload) -> | |
payload match { | |
case is Array -> payload map expandXmlAttrs($) | |
case is Object -> payload mapObject { | |
(($$): expandXmlAttrs($)) if ($$.@ == null), | |
(($$): { | |
value: expandXmlAttrs($), | |
($.@) | |
}) if ($$.@ != null) | |
} | |
else -> payload | |
} | |
--- | |
expandXmlAttrs(payload) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The function allows easy expansion of XML to JSON while preserving attributes. Currently, if there are no attrs, value is just passed as key. If there are attributes, value is passed as object with value key and attributes expanding into this object.
Example input:
Example output:
For a more consistent, but larger data output, consider changing the function to something like this:
Which means all keys will have an object with a value key, and potentially attribute keys.
Same input, different output: