<div class="codetitle"> <span><a style="CURSOR: pointer" data="2483" class="copybut" id="copybut2483" onclick="doCopy('code2483')"><u>复制代码</u></a></span> 代码如下:</div> <div class="codebody" id="code2483"> <br> <br> <br> <br><meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <br><meta name="author" content="Nancle from CAU CS 101"> <br><title>JSON序列化与解析(原生JS + Object对象拓展方法)【IE6和chrome测试通过】</title> <br> <br><script type="text/javascript"> <BR>var ele = { <BR>x:11, <BR>y:'string', <BR>z:{x:11, y:'string'} <BR>} <BR>toJSON = function(obj){ <BR>var arr = []; <BR>for(var key in obj){ <BR>var value = obj[key]; <BR>if(value == null){ <BR>value = ''; <BR>}else{ <BR>value = (typeof value === 'string' | typeof value === 'number') <BR>? ('"' + value + '"') : toJSON(value); <BR>} <BR>var str = '"' + key + '":' + value; <BR>arr.push(str); <BR>} <BR>return '{' + arr.join(',') + '}'; <BR>} <BR>var str = toJSON(ele); <BR>alert('装换成的字符串是: ' + str ); <BR>var ele2 = eval('(' + str + ')'); <BR>alert('解析字符串得到js对象: x=' + ele2.x + ',y=' + ele2.y + ',z=' + ele2.z); <BR></script> <br> <br> <br> <br> </div>