Created
August 21, 2015 05:37
-
-
Save borgle/802a5261f04cd374a03d to your computer and use it in GitHub Desktop.
收集并完善的一份jquery插件,将json对象转换为字符串功能,支持低版本浏览器。来源:https://gist.github.com/chicagoworks/754454
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.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