I would like to persist a complex object tree as a string, that can work in a browser or in nodejs. The most obvious thing to do is to use JSON.stringify and JSON.parse - however I just get the values of the strings and numbers and so on, but what kind of object was persisted is not stored, and so cannot be restored. Or rather the values are restored but not the function bindings. What would be the correct way to do persist objects which have method functions in JavaScript?
You can already do what you want with JSON.stringify()
and JSON.parse()
.
JSON.stringify()
checks for a .toJSON()
method on objects you pass to it. So if your object/class/whatever implements that method, you can return whatever serialized format you want. That can include the object/class type and other information needed to unserialize it later on.
JSON.parse()
has a reviver function parameter that allows you to manually return the unserialized value for each parsed JSON value.
So for example, in your .toJSON()
you might return an object containing your data, but also a __objType
property that is set to the object type name. Then in your reviver function, you check if the value is an object and if it has an __objType
property. If it does, then you check the value of that property and unserialize it appropriately (you could even write a .fromJSON()
in your object/class that does this for you, but unlike .toJSON()
, .fromJSON()
has no special meaning).