浅谈json

JavaScript对象表示法,JavaScript Object Nation。json是轻量级的文本数据交换格式。它比XML更容易解析。今天就通过一个小例子,简要介绍一下json的解析。

下面看一个json解析的小例子:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
	<title></title>
		<script language="javascript" type="text/javascript">
			function jsonDemo(){
				var txt = '{"employees":[' 
					+'{"firstName":"Bill","lastName":"Gates"},' 
					+'{"firstName":"George","lastName":"Bush"},' 
					+'{"firstName":"Thomas","lastName":"Carter"}]}';	
				
				var obj=eval("("+txt+")");
				document.getElementById("fName").innerHTML=obj.employees[0].firstName;
				document.getElementById("lName").innerHTML=obj.employees[0].lastName;
			}
		</script>
	
<body onload="jsonDemo();">
<div>
	<h2>通过 JSON 字符串来创建对象</h2>
	<div>
		<p>
			<div>
				First Name: <span id="fName"></span>
			</div>
			<br /> 
			
			<div>
				Last Name: <span id="lName"></span>
			</div>
			<br /> 
		</p> 
	</div>
</div>
</body>
</html>

上面例子中,我们用eval来对json进行解析,进而转化成JavaScript对象。

你可能感兴趣的:(浅谈json)