json数据处理例子

来源:互联网 发布:吴昕 潘玮柏 知乎 编辑:程序博客网 时间:2024/04/28 04:07

前提:引入json.js,官网下载

<!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=gb2312" />
<title>无标题文档</title>
<script src="json.js"></script>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script>
var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
  { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
  { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
  ],
  "authors": [
  { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
  { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
  { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
  ],
  "musicians": [
  { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
  { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
  ] };
alert(people.programmers[0].lastName);//访问成员people.programmers[0].lastName
alert( people.toJSONString()); //访问成员数组的长度people.programmers.length,只有是数组的才有length属性
var jsonStr=people.toJSONString();转化成字符串people.toJSONString()变量jsonStr
var jsonObj=eval("("+jsonStr+")");//将 jsonStr转成json对象 ;注意要加括号


 
</script>
</head>


<body>
<h2>json数据处理例子</h2>
<p>前提:引入json.js文件,官网提供</p>
<p>访问成员people.programmers[0].lastName</p>
<p>访问成员数组的长度people.programmers.length,只有是数组的才有length属性</p>
<p>转化成字符串people.toJSONString()变量jsonStr</p>
<p>转化成json字符串jsonStr转成json对象:var jsonObj=eval("("+jsonStr+")");注意要加括号</p>
<h2>使用$.each处理json:</h2>
<div id="show">each输出结果为:</div>

<script>

// 注意,这个要放在文件后,否则如果div未加载则获取不到div用来显示

$.each(people.programmers,function(idx,item){ 
 $("#show").append(" <b>"+item.firstName+"</b>");
});
</script>
</body>
</html>
原创粉丝点击