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.
You could use a regular expression to replace the keys, for example: String str = myJsonObject. toString(); str = str.
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.
const arr = JSON.parse(json);
obj.id = obj._id; delete obj._id;
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With