How to wrap complex objects as strings in javascript
I would like to store a complex tree of objects as a string that can run in the browser or in nodes. The most obvious thing is to use JSON.stringify and JSON.parse - however I just get the values ββof strings and numbers and so on, but which object was saved is not saved and therefore cannot be restored. Rather, the values ββare restored, but not assigned to functions. What would be the correct way to save objects that have method functions in JavaScript?
source to share
You can already do what you want with JSON.stringify()
and JSON.parse()
.
JSON.stringify()
checks the .toJSON()
method of the objects you pass to it. Therefore, if your object / class / whatever implements this method, you can return any serial format you want. This can include the type of the object / class and other information needed to unserialize it later.
JSON.parse()
has a function parameter reviver that allows you to manually return a non-serialized value for each parsing of a JSON value.
So, for example, in yours, .toJSON()
you can return an object containing your data, but also a property __objType
that is given an object type name. Then, in your reviver function, you check if this value is an object and if it has a property __objType
. If so, then you check the value of this property and unserialize it accordingly (you can even write .fromJSON()
to your object / class that will do it for you, but unlike .toJSON()
, it .fromJSON()
doesn't really matter).
source to share
If your functions are typically static methods for manipulation / transformation, you should just be able to reinitialize the classes from the JSON data.
Perhaps you should create a function exportToJson
and importFromJson
eg.
function SomeClass(json) {
var base = this;
base.a = 'asdf';
base.b = 'fdsa';
base.export = function () {
return JSON.stringify({
a: base.a,
b: base.b
});
};
base.imports = function (js) {
base.a = js['a'];
base.b = js['b'];
};
if (typeof json !== 'undefined') {
base.imports(json);
}
}
(not the nicest solution, but this is also StackOverflow: p)
source to share