How to Rename JSON Keys in Your Data with DataWeave
This article will explain how one can rename JSON Keys or Fields from the payload containing JSON data, without affecting the other fields present in the payload.
This example includes the below-mentioned functions:
mapObject
to go through thekey:value
pairs in a JSON object.if
by itself to determine when to change the name of a key.if
withand
to retain the name of all keys except the two with new names.as
to coerce the type of the keys into a String.
Input JSON Payload
{
"Employee":[
{
"employeeId":1,
"firstName":"Alex",
"lastName":"Davis",
"email":"alex@abc.com",
"dob":"12/14/1998"
},
{
"employeeId":2,
"firstName":"John",
"lastName":"Dann",
"email":"john@abc.com",
"dob":"12/14/1995"
}]
}
Dataweave Logic
%dw 2.0
output application/json
---
payload.Employee map (emp) -> {
(emp mapObject (value, key) -> {
(id: value) if(key as String == 'employeeId'),
((key):value) if(key as String !='employeeId')
})
}
Output JSON
[
{
"id": 1,
"firstName": "Alex",
"lastName": "Davis",
"email": "alex@abc.com",
"dob": "12/14/1998"
},
{
"id": 2,
"firstName": "John",
"lastName": "Dann",
"email": "john@abc.com",
"dob": "12/14/1995"
}
]
There is another approach to the same problem using the pattern matching mechanism, The example includes the below-mentioned functions and statements:
mapObject
to go through thekey:value
pairs in a JSON object.match
on each key in the input.case
statements to change the name of matching keys in the input.else
statement to retain the name of keys that do not require a name change.
%dw 2.0
output application/json
fun renameKey(key: Key) = key match {
case "employeeId" -> "id"
else -> (key)
}
---
payload.Employee map (emp) ->
emp mapObject (value, key) -> {
(renameKey(key)) : value
}