7

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;
    }
}
salacis
  • 205
  • 1
  • 3
  • 11

1 Answers1

15

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"}" 
dandavis
  • 16,370
  • 5
  • 40
  • 36