首页 > 代码库 > 简单的Json数据

简单的Json数据

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <script type="text/javascript" src="http://www.mamicode.com/js/jquery-1.7.2.js"></script>
  <script type="text/javascript" src="http://www.mamicode.com/json2.js"></script>
    <title>jsonTest.html</title>
	<script type="text/javascript">
		function testJson(){
			var jsonTest=‘{"name":"aaa","age":12}‘;				//定义一个简单的字符串类型
			var jsonObj=JSON.parse(jsonTest);					//转换为json对象
			$("#div1").html("年龄"+jsonObj.name);				//读取并输出json元素
			
			
			
			var jsonTests=‘[{"name":"aaa","age":12},{"name":"bbb","age":25},{"name":"ccc","age":35},{"name":"ddd","age":45}]‘			//定义一个json数组对象的字符串
			var jsonObjs=JSON.parse(jsonTests);			//转换为json数组对象
			for ( var i = 0; i < jsonObjs.length; i++) {
				
					$("#div2").html($("#div2").html()+"<br/>"+"名字"+jsonObjs[i].name+"年龄"+jsonObjs[i].age);				//读取json数组中的所有json对象以及json对象的元素
				
			}
			var jsonTestss={"yuangong":[{"name":"aaa","age":12},{"name":"bbb","age":25},{"name":"ccc","age":35},{"name":"ddd","age":45}],		
			
				"xuesheng":[{"name":"xuesheng1","age":22},{"name":"xuesheng2","age":20}]				//定义一个组合类型的json对象
			};
			$("#div3").html(jsonTestss.yuangong.length+"<br>");
			for ( var i = 0; i < jsonTestss.yuangong.length; i++) {
					$("#div3").html($("#div3").html()+"<br/>"+"名字"+jsonTestss.yuangong[i].name+"年龄"+jsonTestss.yuangong[i].age);
					}
			
		}
	</script>

  </head>
  
  <body onl oad="testJson()">
 		<div id="div1"></div>
 		<div id="div2"></div>
 		<div id="div3"></div>
  </body>
</html>

  

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>jQueryJson.html</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
   <script type="text/javascript" src="http://www.mamicode.com/js/jquery-1.7.2.js"></script>
    <script type="text/javascript">
    $(function(){
    
    	var jsons=‘[{"name":"aaa","age":12},{"name":"bbb","age":25},{"name":"ccc","age":35},{"name":"ddd","age":45}]‘		//定义一个json数组对象
    	var jsonObj=eval(jsons);
    	for ( var i = 0; i < jsonObj.length; i++) {
			$("#div1").html($("#div1").html()+"<br/>"+"姓名"+jsonObj[i].name+"年龄"+jsonObj[i].age);
			
		}
			$.each(jsonObj,function(i){
				$("#div1").html($("#div1").html()+"<br/>"+"姓名"+jsonObj[i].name+"年龄"+jsonObj[i].age);
			})
			
			$.each(jsonObj,function(i,n){
				$("#div1").html($("#div1").html()+"<br/>"+"下标为"+i+"的人的姓名"+n.name+"年龄"+n.age);
			})
    });
    
    </script>
  </head>
  
  <body>
  <div id="div1"></div>
  </body>
</html>

  

简单的Json数据