本文出自:http://blog.youkuaiyun.com/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>
本文介绍了一种使用原生JavaScript实现的JSON序列化与解析的方法。通过自定义函数toJSON进行对象转字符串操作,并利用eval函数完成字符串到对象的转换。此方法适用于IE6和Chrome等浏览器。
163

被折叠的 条评论
为什么被折叠?



