Created
May 3, 2011 17:24
-
-
Save clementi/953765 to your computer and use it in GitHub Desktop.
jQuery Stringify
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* jQuery.stringify (https://gist.github.com/953765) | |
* | |
* converted stringify() to jQuery plugin. | |
* serializes a simple object to a JSON formatted string. | |
* uses browser's native JSON.stringify() if it exists. | |
* 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: | |
* - https://gist.github.com/754454 | |
* - http://blogs.sitepointstatic.com/examples/tech/json-serialization/json-serialization.js | |
*/ | |
jQuery.extend({ | |
stringify: this.JSON && this.JSON.stringify ? this.JSON.stringify : function stringify(obj) { | |
var t = typeof(obj); | |
if (t != "object" || obj === null) { | |
if (t == "string") | |
obj = '"' + obj + '"'; | |
return String(obj); | |
} | |
else { | |
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 ? "]" : "}"); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment