Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename JSON key

Tags:

json

I have a JSON object with the following content:

[   {     "_id":"5078c3a803ff4197dc81fbfb",     "email":"[email protected]",     "image":"some_image_url",     "name":"Name 1"   },   {     "_id":"5078c3a803ff4197dc81fbfc",     "email":"[email protected]",     "image":"some_image_url",     "name":"Name 2"   } ] 

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

[   {     "id":"5078c3a803ff4197dc81fbfb",     "email":"[email protected]",     "image":"some_image_url",     "name":"Name 1"   },   {     "id":"5078c3a803ff4197dc81fbfc",     "email":"[email protected]",     "image":"some_image_url",     "name":"Name 2"   } ] 

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

Thanks.

like image 584
duy Avatar asked Nov 15 '12 04:11

duy


People also ask

How do I rename a key in JSON?

You could use a regular expression to replace the keys, for example: String str = myJsonObject. toString(); str = str.

How do I change the value of a JSON object?

Array value of a JSON object can be modified. It can be simply done by modifying the value present at a given index. Note: If value is modified at an index which is out of the array size, then the new modification will not replace anything in the original information but rather will be an add-on.


1 Answers

  1. Parse the JSON
const arr = JSON.parse(json); 
  1. For each object in the JSON, rename the key:
obj.id = obj._id; delete obj._id; 
  1. 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 );
like image 149
Paul Avatar answered Oct 03 '22 23:10

Paul