How to rename JSON key
- Parse the JSON
const arr = JSON.parse(json);
- For each object in the JSON, rename the key:
obj.id = obj._id;
delete obj._id;
- Stringify the result
All together:
function renameKey ( obj, oldKey, newKey ) {
obj[newKey] = obj[oldKey];
delete obj[oldKey];
}
const json = `
[
{
"_id":"5078c3a803ff4197dc81fbfb",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 1"
},
{
"_id":"5078c3a803ff4197dc81fbfc",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 2"
}
]
`;
const arr = JSON.parse(json);
arr.forEach( obj => renameKey( obj, '_id', 'id' ) );
const updatedJson = JSON.stringify( arr );
console.log( updatedJson );
In this case it would be easiest to use string replace. Serializing the JSON won't work well because _id will become the property name of the object and changing a property name is no simple task (at least not in most langauges, it's not so bad in javascript). Instead just do;
jsonString = jsonString.replace("\"_id\":", "\"id\":");
As mentioned by evanmcdonnal, the easiest solution is to process this as string instead of JSON,
var json = [{"_id":"5078c3a803ff4197dc81fbfb","email":"[email protected]","image":"some_image_url","name":"Name 1"},{"_id":"5078c3a803ff4197dc81fbfc","email":"[email protected]","image":"some_image_url","name":"Name 2"}];
json = JSON.parse(JSON.stringify(json).split('"_id":').join('"id":'));
document.write(JSON.stringify(json));
This will convert given JSON data to string and replace "_id" to "id" then converting it back to the required JSON format. But I used split
and join
instead of replace
, because replace
will replace only the first occurrence of the string.
Try this:
let jsonArr = [
{
"_id":"5078c3a803ff4197dc81fbfb",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 1"
},
{
"_id":"5078c3a803ff4197dc81fbfc",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 2"
}
]
let idModified = jsonArr.map(
obj => {
return {
"id" : obj._id,
"email":obj.email,
"image":obj.image,
"name":obj.name
}
}
);
console.log(idModified);