JSON.parse使用reviver函数

sal*_*cis 3 javascript

如何使用JSON.parse reviver方法编辑某个值.我只想编辑声明为lastname的每个键,然后返回新值.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

dan*_*vis 9

在检查特殊情况后,您只需要在默认情况下传回未修改的值:

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"}" 
Run Code Online (Sandbox Code Playgroud)