How to serialize & deserialize JavaScript objects?

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.

Leave a Comment

tech