JSON.parse using reviver function

前端 未结 1 1763
死守一世寂寞
死守一世寂寞 2021-01-13 05:21

How to use JSON.parse reviver method to edit a certain value. I just want to edit every key which is declared as lastname and than return the new value.

var          


        
相关标签:
1条回答
  • 2021-01-13 06:09

    After checking for the special case(s), you simply need to pass back unmodified values by default:

    var myObj = new Object();
    myObj.firstname = "mike";
    myObj.lastname = "smith";
    
    var jsonString = JSON.stringify(myObj);
    var jsonObj = JSON.parse(jsonString, dataReviver);
    
    function dataReviver(key, value)
    { 
        if(key == 'lastname')
        {
            var newLastname = "test";
            return newLastname;
        }
    
      return value;  // < here is where un-modified key/value pass though
    
    }
    
    JSON.stringify(jsonObj )// "{"firstname":"mike","lastname":"test"}" 
    
    0 讨论(0)
提交回复
热议问题