Serialize JSON with jQuery

I was reading an interesting article on about JSON serialization and decided to wrap it up in as a jQuery extension to include in my development library.  Most of the code has been borrowed from the original implementation, I’ve just jQueryifed things. So here it is:

jQuery(function($) {
    $.extend({
        serializeJSON: function(obj) {
            var t = typeof(obj);
            if(t != "object" || obj === null) {
                // simple data type
                if(t == "string") obj = '"' + obj + '"';
                return String(obj);
            } else {
                // array or object
                var json = [], arr = (obj && obj.constructor == Array);
 
                $.each(obj, function(k, v) {
                    t = typeof(v);
                    if(t == "string") v = '"' + v + '"';
                    else if (t == "object" & v !== null) v = $.serializeJSON(v)
                    json.push((arr ? "" : '"' + k + '":') + String(v));
                });
 
                return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
            }
        }
    });
});

And to use it, you would do something like

$(document).ready(function () {
 
    var obj1 = {
        b1: true,
        s1: "text string",
        n1: 12345,
        n2: null,
        n3: undefined,
        a1: [1, 1, 2, 3, 5, 8, [13, 21, 34]],
        o1: {
            a: [3, 2, 1],
            b: {
                c: 42,
                d: [3.14, 1.618]
            }
        }
    };
 
    alert($.serializeJSON(obj1));
 
});
This entry was posted in jQuery and tagged , , . Bookmark the permalink.

3 Responses to Serialize JSON with jQuery

Leave a Reply

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