简体   繁体   中英

JSON.parse using reviver function

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 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;
    }
}

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"}" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM