#Rename a key in existing json

1 messages · Page 1 of 1 (latest)

fossil hedge
#

I have a array of json that contains something like
[ { "sys_id": "711942771b8b9d182a5ea971604bcb1d",
"COMMON_ID": "500709491"
},{ "sys_id": "49cde5621b6791902a5ea971604bcb85",
"COMMON_ID": "500724880"
}]

I would like to rename the key COMMON_ID to EMPLID, so the output would be
[ { "sys_id": "711942771b8b9d182a5ea971604bcb1d",
"EMPLID": "500709491"
},{ "sys_id": "49cde5621b6791902a5ea971604bcb85",
"EMPLID": "500724880"
}]

I must not be searching the documentaion with the correct keywords, because I can't seem to find anything.

Any help would be appreciated.

fossil hedge
#

I found some info after searching for the data mapper and that was the piece I needed to create:

function transform_COMMON_ID(Reconcilliation_common_id data) returns Reconcilliation => {
emplid: data.COMMON_ID,
sys_id: data.sys_id
};

I also created the type definition for Reconcilliation_common_id with the emplid instead of the COMMON_ID.

brisk prawn
#

You can use this way also to rename the key

import ballerina/io;

map<json> x = {  
    "sys_id": "711942771b8b9d182a5ea971604bcb1d",
    "COMMON_ID": "500709491" 
};

public function main() {
    x["EMPLID"] = "500709491";
    io:println(x); // prints {"sys_id":"711942771b8b9d182a5ea971604bcb1d","COMMON_ID":"500709491","EMPLID":"500709491"}
}
velvet minnow
#

@brisk prawn that adds a key not renames it right? AFAIK we can't rename a key (as that changes the type of the record) - you have to create a new value with new keys as @fossil hedge has done with an expression function (type mapping).

cerulean jolt
#

@fossil hedge @velvet minnow creating a new value works. But also we can remove the keys if your are using a map. You can use map.remove function for this.

map<json> m = {sys_id: "711942771b8b9d182a5ea971604bcb1d", common_id: "500709491"};
m["emplid"] = m?.common_id;
_ = m.remove("common_id");