How to rename JSON key

后端 未结 11 749
名媛妹妹
名媛妹妹 2020-11-27 12:46

I have a JSON object with the following content:

[
  {
    \"_id\":\"5078c3a803ff4197dc81fbfb\",
    \"email\":\"user1@gmail.com\",
    \"image\":\"some_imag         


        
11条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 13:31

    As mentioned by evanmcdonnal, the easiest solution is to process this as string instead of JSON,

    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"}];
        
    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.

提交回复
热议问题