Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.parse using reviver function

Tags:

javascript

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;
    }
}
like image 480
salacis Avatar asked Jun 23 '14 19:06

salacis


1 Answers

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"}" 
like image 85
dandavis Avatar answered Oct 02 '22 17:10

dandavis