Skip to content

Instantly share code, notes, and snippets.

@simplelife7
Created September 18, 2014 06:23
Show Gist options
  • Save simplelife7/430b3f3c0e39d653e125 to your computer and use it in GitHub Desktop.
Save simplelife7/430b3f3c0e39d653e125 to your computer and use it in GitHub Desktop.
【JS】JSON转换成字符串,兼容低级浏览器
function $transJson2str(o) {
if (o == undefined) {
return "";
}
var r = [];
if (typeof o == "string") return "\"" + o.replace(/([\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
if (typeof o == "object") {
if (o.nodeName){
r.push(["document node", "nodeName:"+o.nodeName, "id:"+o.id, "class:"+o.className].join('-'));
r = "{" + r.join() + "}";
}
else if (!o.sort) {
for (var i in o)
r.push("\"" + i + "\":" + $transJson2str(o[i]));
if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
r.push("toString:" + o.toString.toString());
}
r = "{" + r.join() + "}";
} else {
for (var i = 0;
i < o.length;
i++)
r.push($transJson2str(o[i]));
r = "[" + r.join() + "]";
}
return r;
}
return o.toString().replace(/\"\:/g, '":""');
}
var obj = {"a":"abc"},
str;
str = $transJson2str(obj);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment