Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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).

question from:https://stackoverflow.com/questions/3608545/how-to-serialize-deserialize-javascript-objects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
222 views
Welcome To Ask or Share your Answers For Others

1 Answer

In general, there's no way (in a browser) so serialize objects with functions attached to them, since every function has a reference to it's outer scope. If the function references any of those variables, they won't exist anymore when you deserialize it.

What I would to 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...