Reconstructing JS objects from JSON

The data of my view models is, like everyone else’s, serialised as JSON across the wire.

It is well understood that JSON.stringify(object) serialises only members that have a non-null value that is not a Function. Thus, JSON.parse(JSON.stringify(someObject)) will remove all the methods from the object.

My current implementation has each graph node implemented as a Typescript class with Serialise and Deserialise methods. JQuery.ajax calls a Web API and implicitly parses the resultant JSON into a DAG of object definitions, each of which has a Type property indicating which type of class it was prior to serialisation. I have a map of constructors indexed by name and the appropriate constructor is retrieved and the data passed as the constructor parameter.

Depending on type there may be children; if so things proceed recursively down the graph.

I have been wondering whether, rather than copy all the property values, I couldn’t just assign an appropriate prototype. Bring the mountain to Mahomed, you might say. This would eliminate quite a bit of clutter in my codebase.

As I write it occurs to me that I could use $.extend, but I’m progressively weeding jQuery out of my codebase so this would be a retrograde step.

  • Is there any known peril in my proposition of diddling the prototype?
  • Does anyone have a better idea? Other than $.extend, I mean. Something TypeScripty, by preference.

Reconstructing JS objects from JSON