JSON.parse, JS typecasting, and revivers JSON.parse, JS typecasting, and revivers json json

JSON.parse, JS typecasting, and revivers


JSON is a format for raw data. It's very primitive. It supports dictionaries (aka. javascript objects, hashes, associative arrays), arrays, strings, numbers, booleans and null. That's it. The reason it doesn't do more is that those primitives are language agnostic, and nearly all programming language have built in tools to handle those types of data.

If you had other notation like "class" then suddenly it becomes very bound to specific languages or codeboases, and lose it's wide and generic applicability.

So think of JSON as simple raw data. JSON is not instance marshalling or complete object serialization. So yes you need to write "revivers" if you intend to serialize JS objects instantiated from constructors.

This is the approach things like backbone.js take:

new Book({  title: "One Thousand and One Nights",  author: "Scheherazade"});

You simply pass your plain object of data (the result of your JSON.parse()) to the call to your constructor of choice. From there you can do any number of things to read it's values into your new object.

Javascript has no standard way of Marshalling whole objects like you can in ruby with Marhsal.dump(obj) for instance.


EDIT: One last major point...

Javascript objects don't have a "type" as you would think of it in other languages. A Javascript object is simply a a dictionary of key/value pairs. When you do something like new SomeClass() you get a new object, that has a special prototype property that points to the prototype property of the SomeClass function object. Wether an object is an instance of SomeClass is less of a clear cut question than you may think at first glance.

Instead you may ask "What is my constructor function object?" or "What objects are in my prototype chain?"

So if you wanted to convey "type" in JSON, which is stored as a string, then how would you store a reference to a prototype object? Maybe the prototype object is not named in the global scope at all, and only available via closure? Then when you write that out to string, you have no way of referencing that prototype object anymore at all.

The point is that javascripts prototypical approach to object instantiation, combined with it's closure based lexical scoping and the fact that objects hold their values more like C pointers than literal values, makes it very very hard to fully serialize an object out to a location external to the VM.