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"}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With