Monday, May 20, 2024
92
rated 0 times [  98] [ 6]  / answers: 1 / hits: 67137  / 14 Years ago, tue, august 31, 2010, 12:00:00

I need to serialize and deserialize JavaScript objects to store them in a DB.


Note that these objects contain functions, so I can't store them as JSON, so I can't use json2.js.


What's the state of the art in [de]serialization of JavaScript objects (in JavaScript of course).


More From » serialization

 Answers
34

In general, there's no way (in a browser) to serialize objects with functions attached to them: Every function has a reference to its outer scope, that scope won't exist when you deserialize it, so serialized references to that scope will be invalid.


What I would do is use the built-in (or json2.js) JSON.stringify and JSON.parse functions with the replacer and reviver parameters. Here's a partial example of how it would work:


JSON.stringify(yourObject, function(name, value) {
if (value instanceof LatLng) { // Could also check the name if you want
return 'LatLng(' + value.lat() + ',' + value.lng() + ')';
}
else if (...) {
// Some other type that needs custom serialization
}
else {
return value;
}
});

JSON.parse(jsonString, function(name, value) {
if (/^LatLng(/.test(value)) { // Checking the name would be safer
var match = /LatLng(([^,]+),([^,]+))/.exec(value);
return new LatLng(match[1], match[2]);
}
else if (...) {
...
}
else {
return value;
}
});

You can use any serialization format you want in your custom types. The "LatLng(latitude,longitude)" format is just one way of doing it. You could even return a JavaScript object that can be serialized to JSON natively.


[#95749] Saturday, August 28, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
carolinabritneyp

Total Points: 75
Total Questions: 102
Total Answers: 105

Location: Armenia
Member since Fri, Apr 16, 2021
3 Years ago
;