Skip to content

Instantly share code, notes, and snippets.

@borgle
Created August 21, 2015 05:37
Show Gist options
  • Save borgle/802a5261f04cd374a03d to your computer and use it in GitHub Desktop.
Save borgle/802a5261f04cd374a03d to your computer and use it in GitHub Desktop.
收集并完善的一份jquery插件,将json对象转换为字符串功能,支持低版本浏览器。来源:https://gist.github.com/chicagoworks/754454
jQuery.extend({
stringify : function stringify(obj) {
if ("JSON" in window) {
return JSON.stringify(obj);
}
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"' + obj.replace(/"/g,'\\\"') + '"';
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.replace(/"/g,'\\\"') + '"';
} 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