日期:2014-05-16 浏览次数:20345 次
本文出自:http://blog.csdn.net/nancle/article/details/11121115
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="author" content="Nancle from CAU CS 101" /> <title>JSON序列化与解析(原生JS + Object对象拓展方法)【IE6和chrome测试通过】</title> </head> <script type="text/javascript"> var ele = { x:11, y:'string', z:{x:11, y:'string'} } toJSON = function(obj){ var arr = []; for(var key in obj){ var value = obj[key]; if(value == null){ value = ''; }else{ value = (typeof value === 'string' | typeof value === 'number') ? ('"' + value + '"') : toJSON(value); } var str = '"' + key + '":' + value; arr.push(str); } return '{' + arr.join(',') + '}'; } var str = toJSON(ele); alert('装换成的字符串是: ' + str ); var ele2 = eval('(' + str + ')'); alert('解析字符串得到js对象: x=' + ele2.x + ',y=' + ele2.y + ',z=' + ele2.z); </script> <body> </body> </html>