duy duy - 3 months ago 25
JSON Question

How to rename JSON key

I have a JSON object with the following content:

[
{
"_id":"5078c3a803ff4197dc81fbfb",
"email":"user1@gmail.com",
"image":"some_image_url",
"name":"Name 1"
},
{
"_id":"5078c3a803ff4197dc81fbfc",
"email":"user2@gmail.com",
"image":"some_image_url",
"name":"Name 2"
}
]


I want to change the "_id" key to "id" so it would become

[
{
"id":"5078c3a803ff4197dc81fbfb",
"email":"user1@gmail.com",
"image":"some_image_url",
"name":"Name 1"
},
{
"id":"5078c3a803ff4197dc81fbfc",
"email":"user2@gmail.com",
"image":"some_image_url",
"name":"Name 2"
}
]


How would I do that either with Javascript, jQuery or Ruby, Rails?

Thanks.

Answer
var json = '[{"_id":"5078c3a803ff4197dc81fbfb","email":"user1@gmail.com","image":"some_image_url","name":"Name 1"},{"_id":"5078c3a803ff4197dc81fbfc","email":"user2@gmail.com","image":"some_image_url","name":"Name 2"}]';

var obj = JSON.parse(json)[0];
obj.id = obj._id;
delete obj._id;

json = JSON.stringify([obj]);

This changes json to:

[{"email":"user1@gmail.com","image":"some_image_url","name":"Name 1","id":"5078c3a803ff4197dc81fbfb"}]

Since order doesn't have meaning in a name/value pair in JSON, this is the same as your desired result.