赵工的个人空间


网络课堂部分转网页计算部分转编程演练

 JS函数库使用技巧

首页 > 网络课堂 > JS函数库使用技巧 > jQuery解析json数据
jQuery解析json数据

JSON是JavaScript Object Notation的缩写,是基于JavaScript的数据格式,非常易于使用,得到浏览器的广泛支持。JSON是基于键/值对构建的,冒号用于分隔键和它的值,逗号用于分隔每个数据对,所有的键和字符串都被封装在双引号中,所有数据被包含在大括号中,可以使用中括号与大括号在JSON中嵌套数组与对象。

因为JSON数据格式是基于JavaScript的,可以直接读取,只需要知道其中的数据结构和目标键。JSON数据在JavaScript中是作为一个Object来处理的,可以把通过构造一个符合JSON格式的字符串,然后使用JSON.parse()方法或jQuery中的parseJSON()函数把这个符合格式的字符串转换为JSON对象;当然,也可以使用为JSON对象各个键赋值的方法构造JSON对象。

JSON数据可以作为文件格式异步加载,使用的方法为:

$.getJSON("regiona.json",function(data){......});

然后就可以使用jQuery的each()函数遍历数据data:

$.each(data.sales.region,function(k,v){

在each()循环中同时提供JSON中的键k和值v,得到数据后就可以用来构建DOM,进一步可以将获取的数据在canvas中显示为图表,如柱状图。示例:

$(document).ready(function(){
  var theChart=document=document.getElementById('chart');
  var chartHeight=400;;
  var theWidth=75;
  var theSpace=100;
  var theX=0;
  var theY=0;
  var theFills=['orange','blue','red','green'];
  var i=0;
  if(theChart.getContext){
    var theContext=theChart.getContext('2d');
    $.getJSON("region.json",function(data){;
      $.each(data.sales.region,function(k,v){
        var theTerritory=v.territory;
        var theHeight=v.parseInt(v.amount.replace(/,/g,''))/1000;
        var theY=chartHeight-theHeight;
        var theX=theX+theSpace;
        theContext.fillStyle=theFills[i];
        theContext.fillRect(theX,thY,theWidth,theHeight);
        theContext.fillStyle='black';
        theContext.font='12pt Arial';
        theContext.fillText(theTerritory,theX,theY-20);
        ++i;
      });

    });
  }
});

Copyright@dwenzhao.cn All Rights Reserved   备案号:粤ICP备15026949号
联系邮箱:dwenzhao@163.com  QQ:1608288659