Object转JSON串

2010-04-26 16:43:02

写得很粗糙,未对null, undefined等特殊值处理,以后用的时候再改良! 如果谁有更好,更官方的,帖个地址! 谢谢了! [code]var JSON = { Object2JSON:function(obj){ var res = []; if (obj instanceof Array) { for(var i=0;i<obj.length;i++){ var e = obj[i]; var str = &#39;&#39;; switch (typeof e) { case &#34;boolean&#34;: str = Boolean(e);break; case &#34;number&#34;: str = Number(e);break; case &#34;string&#34;: str = &#39;&#34;&#39; + e + &#39;&#34;&#39;;break; case &#34;object&#34;: str = JSON.Object2JSON(e);break; default: str = e; } res.push(str); } res = res.join(&#34;,&#34;); res = &#39;[&#39;+res+&#39;]&#39;; } else { for (var i in obj) { var e = obj[i]; var str = &#39;&#39;; switch (typeof e) { case &#34;boolean&#34;: str = &#39;&#34;&#39; + i + &#39;&#34;:&#39; + Boolean(e);break; case &#34;number&#34;: str = &#39;&#34;&#39; + i + &#39;&#34;:&#39; + Number(e);break; case &#34;string&#34;: str = &#39;&#34;&#39; + i + &#39;&#34;:&#34;&#39; + e + &#39;&#34;&#39;;break; case &#34;object&#34;: str = JSON.Object2JSON(e);break; default: str = e; } res.push(str); } res = res.join(&#34;,&#34;); res = &#39;{&#39;+res+&#39;}&#39;; } return res; } [/code] 测试代码: var arr = [1,{&#34;a&#34;:&#34;fuck&#34;},3] var obj = {a:1,b:2,&#34;aaa&#34;:&#34;111&#34;,log:arr}; JSON.Object2JSON(obj) trace: -------------------------------- &#34;{&#34;a&#34;:1,&#34;b&#34;:2,&#34;aaa&#34;:&#34;111&#34;,[1,{&#34;a&#34;:&#34;fuck&#34;},3]}&#34;