%dw 2.0
output application/json
import * from dw::core::Objects
import * from dw::core::Strings
fun toCamelCase(str: String) = camelize(str)
fun convertKeys(obj: Any): Any =
obj match {
case is Object ->
obj mapObject ((value, key) ->
{
(toCamelCase(key)): convertKeys(value)
}
)
case is Array ->
obj map convertKeys($)
else -> obj
}
---
convertKeys(inputJson)
In this script, we use a match expression to handle three cases: when the input is an object, when the input is an array, and when the input is neither an object nor an array. For objects, we use mapObject to iterate over the key-value pairs, and we apply the camelize function to each key. For arrays, we use the map function to apply the convertKeys function recursively to each element in the array. Finally, we return the original input if it’s not an object or an array.
To use this script, you can pass your original JSON object as the payload variable. The output will be a new JSON object with all the keys converted to camel case, including those inside nested JSON objects and nested JSON arrays.