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:

JSON.stringify(object)

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:

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

Short and quick today!

Leave a Reply

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