js:字符串(string)转json

第一种方式:使用js函数eval();

        testJson=eval(testJson);是错误的转换方式。正确的转换方式需要加(): testJson = eval("(" + testJson + ")");

        eval()的速度非常快,但是他可以编译以及执行任何javaScript程序,所以会存在安全问题。在使用eval()。来源必须是值得信赖的。需要使用更安全的json解析器。在服务器不严格的编码在json或者如果不严格验证的输入,就有可能提供无效的json或者载有危险的脚本,在eval()中执行脚本,释放恶意代码。

<html>
<head>
</head>
	<meta charset="GBK">
	<title>StudyDemo01</title>
	<script type="text/javascript" src="jquery-1.8.3.js"></script>
	<script type="text/javascript">
		function ConvertToJsonForJs() {  
			//var testJson = "{ name: '小强', age: 16 }";(支持)  
			//var testJson = "{ 'name': '小强', 'age': 16 }";(支持)  
			var testJson = '{ "name": "小强", "age": 16 }';  
			//testJson=eval(testJson);//错误的转换方式  
			testJson = eval("(" + testJson + ")");  
			alert(testJson.name);  
		}
		ConvertToJsonForJs();
	</script>
<body>
</body>
</html>

第二种方式:使用jquery.parseJSON()方法

        对json的格式要求比较高,必须符合json格式。

<html>
<head>
</head>
	<meta charset="GBK">
	<title>StudyDemo02</title>
	<script type="text/javascript" src="jquery-1.8.3.js"></script>
	<script type="text/javascript">
		function ConvertToJsonForJq() {  
			var testJson = '{ "name": "小强", "age": 16 }';  
			//'{ name: "小强", age: 16 }' (name 没有使用双引号包裹,不支持)  
			//"{ 'name': "小强", 'age': 16 }"(name使用单引号,不支持)  
			testJson = $.parseJSON(testJson);  
			alert(testJson.name);  
		}
		ConvertToJsonForJq();
	</script>
<body>
</body>
</html>

文章来源:http://blog.csdn.net/jjzjjz1/article/details/6334415

猜你喜欢

转载自bijian1013.iteye.com/blog/2271892