Smart Serialization of JSON

Just wanted to point this one out with Chrome moving dom attributes to the prototype chain.

If you’re used to stringifying dom objects for requests either to local/remote storage. You might be doing something like this alot:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

JSON.stringify(object)

[/pastacode]

But what you’ll find with chrome 43+ is that the properties in prototype chain don’t get serialized. This presents a problem. Luckily, there’s some recursive magic that html5 rocks gives us to do out own serializationZ:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

function stringifyDOMObject(object)
{
    function deepCopy(src) {
        if (typeof src != "object")
            return src;
        var dst = Array.isArray(src) ? [] : {};
        for (var property in src) {
            dst[property] = deepCopy(src[property]);
        }
        return dst;
    }
    return JSON.stringify(deepCopy(object));
}
var s = stringifyDOMObject(domObject);

[/pastacode]

Short and quick today!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.