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:
mapObjectto go through thekey:valuepairs in a JSON object.ifby itself to determine when to change the name of a key.ifwithandto retain the name of all keys except the two with new names.asto 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:
mapObjectto go through thekey:valuepairs in a JSON object.matchon each key in the input.casestatements to change the name of matching keys in the input.elsestatement 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
}