日期:2014-05-16  浏览次数:20389 次

求个在IE6、7下可正常使用的JSON对象转换为字符串的方法
1、我要的是json to string,不是string to json
2、JSON.stringify只在IE8以上生效
3、toJSONString就没有成功过,即使是引用了json.js
4、网上搜索的各种自定义方法实现,各有bug出现
http://topic.csdn.net/u/20080804/16/c05b1f32-3fb9-4a4e-bab3-05268bd73d0e.html这个上头是需要先把字符串构建成自定义的JSON,然后再用自定义JSON得到字符串,问题是我没有字符串,我只有标准Json对象,我要字符串

http://hbiao68.iteye.com/blog/1409515那个o.sort不明白,json对象不是没方法?反正异常了



------解决方案--------------------
蛮不错,发出问题解决了就好!
------解决方案--------------------
关注了,jquery的方法确实会和别的一些代码有冲突,混合使用的话出现问题还真不好找
------解决方案--------------------
解决了就好。

function obj2str(o){
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 =="undefined") return "undefined";
if(typeof o == "object"){
if(o===null) return "null";
else if(!o.sort){
for(var i in o)
r.push(i+":"+obj2str(o[i]))
r="{"+r.join()+"}"
}else{
for(var i =0;i<o.length;i++)
r.push(obj2str(o[i]))
r="["+r.join()+"]"
}
return r;
}
return o.toString();
}