Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the second parameter to JSON.parse called “reviver”?

From the MDN documentation:

  • reviver (Optional)

    If a function, prescribes how the value originally produced by parsing is transformed, before being returned.

Its name strikes me as odd. Maybe I’m missing a metaphor here — why would this be called “reviving” an object? Is there any history to such a transformer function being called a “reviver”? Googling reviver +javascript shows that JSON.parse is basically the only place where this term is used.

like image 783
Lynn Avatar asked Jul 15 '16 08:07

Lynn


2 Answers

The idea is that native Javascript objects, like a Number(42), are your "live" objects. When you serialise those into a JSON representation, they're "dried up", or "dumbed down", or whatever you want to call it. To get your fresh live Javascript objects back, you need to "revive" them from their simple text representation.

This becomes more apparent if you use more complex objects:

function Foo(bar) {
    this.bar = bar;
}

Foo.prototype.baz = function () {
    alert(this.bar);
};

var f = Foo(42);
f.baz();
f = JSON.parse(JSON.stringify(f));
f.baz();  // Nope

To get the original object back which has a baz method, you need to do a little more than just parse it. That's the "reviving" part.

like image 62
deceze Avatar answered Sep 17 '22 02:09

deceze


The parse function is used to create an object from data that has been serialized into a string. By default, all it can do is reconstitute the data into plain objects with a bunch of properties.

Sometimes, you may want to "bring these values back to life" (i.e. revive them) into full-fledged objects with methods, behaviors, etc., or even objects that have a particular type, instead of just the lifeless containers of values that JSON.parse() produces by default.

I would say that's why it's called a reviver.

like image 39
JLRishe Avatar answered Sep 21 '22 02:09

JLRishe