Salient Solutions

wrasslin ones and nones for fun and profit - Sky Sanders' Blog
Get your own ranked flair here
posts - 92, comments - 103, trackbacks - 0

Patching json2.js - deep serialize

 

There are times when you have an object that has been cloned and no longer 'owns' all of it's properties, but you want to serialize it with json2.js.

function clone (object)
{
    /// <summary>
    /// Creates a new Object with prototype = object.
    /// Protypal inheritance.
    /// </summary>
    /// <param name="object" type="Object"></param>
    /// <returns type="Object"></returns>

    function F() { }
    F.prototype = object;
    return new F;
}

The use case in point is a template object which I clone and then tweak a few params before stringing it and pushing it over the wire.

JSON returns only the tweaked properties of course. So I made a very very minor change to json2.js to allow deep serialization.

Listing 2:  stringify() - add 'deep' arg and scope var 'allProps':

JSON.stringify = function(value, replacer, space, deep)
...
...
var i;
gap = '';
indent = '';
allProps = deep;

at the end of str() - add '|| allProps' to hash iterator

for (k in value)
{
    if (Object.hasOwnProperty.call(value, k) || allProps)
    {
        v = str(k, value);
        if (v)
        {
            partial.push(quote(k) + (gap ? ': ' : ':') + v);
        }
    }
}

and that's it.

Print | posted on Thursday, August 27, 2009 1:33 PM |

Feedback

No comments posted yet.

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 5 and 6 and type the answer here:

Powered by: