Python-like pickling of full Javascript objects Python-like pickling of full Javascript objects json json

Python-like pickling of full Javascript objects


It doesn't fit perfectly but you can try to use occamsrazor.js .Doing this you can use JSON serialization:

// this is your costructor functionfunction Circle(attrs){    this.radius = attrs.radius;}Circle.prototype.area = function (){    return this.radius*this.radius*Math.PI;}Circle.prototype.perimeter = function (){    return 2*this.radius*Math.PI;}// this is a validatorfunction hasRadius(obj){    return radius in obj;}// this is your factory functionobjFactory = occamsrazor().addContructor(hasRadius, Circle);// this is your deserialized objectvar json = '{"radius": 10}';// circle now is a full fledged objectvar circle = objFactory(JSON.parse(json));

The drawback is that you don't get a snapshot of an object like using pickle, you recreate a new object. But it may be convenient in some circunstances.


You might want to look at hunterloftis/cryo. From the readme:

Built for node.js and browsers. Cryo is inspired by Python's pickle and works similarly to JSON.stringify() and JSON.parse(). Cryo.stringify() and Cryo.parse() improve on JSON in these circumstances:

  • Undefined
  • Date
  • Infinity
  • Object references
  • Attached properties
  • Functions
  • DOM Nodes

There is a brief discussion with the author at r/programming.

The source is straightforward, no magic.

I haven't tried it yet.