Skip to content

Instantly share code, notes, and snippets.

@chicagoworks
Created December 24, 2010 19:05
Show Gist options
  • Select an option

  • Save chicagoworks/754454 to your computer and use it in GitHub Desktop.

Select an option

Save chicagoworks/754454 to your computer and use it in GitHub Desktop.

Revisions

  1. @cklanac cklanac created this gist Dec 24, 2010.
    41 changes: 41 additions & 0 deletions jQuery.stringify.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@

    /**
    * converted stringify() to jQuery plugin.
    * serializes a simple object to a JSON formatted string.
    * Note: stringify() is different from jQuery.serialize() which URLEncodes form elements
    * UPDATES:
    * Added a fix to skip over Object.prototype members added by the prototype.js library
    * USAGE:
    * jQuery.ajax({
    * data : {serialized_object : jQuery.stringify (JSON_Object)},
    * success : function (data) {
    *
    * }
    * });
    *
    * CREDITS: http://blogs.sitepointstatic.com/examples/tech/json-serialization/json-serialization.js
    */
    jQuery.extend({
    stringify : function stringify(obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
    // simple data type
    if (t == "string") obj = '"' + obj + '"';
    return String(obj);
    } else {
    // recurse array or object
    var n, v, json = [], arr = (obj && obj.constructor == Array);

    for (n in obj) {
    v = obj[n];
    t = typeof(v);
    if (obj.hasOwnProperty(n)) {
    if (t == "string") v = '"' + v + '"'; else if (t == "object" && v !== null) v = jQuery.stringify(v);
    json.push((arr ? "" : '"' + n + '":') + String(v));
    }
    }
    return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
    }
    });