JavaScript解析json格式数据简单示例

以下这串json数据用来存储预加载的图片路径:

var imgData = [
    { name: "p1", src: "images/p1.jpg" },
    { name: "p2", src: "images/p2.jpg" },
    { name: "p3", src: "images/p3.jpg" },
    { name: "p4", src: "images/p4.jpg" },
    { name: "p5", src: "images/p5.jpg" }
   ]

下面这个函数可通过json每行的name来获取该行的路径src,让我们看一下代码:

function getData(name) {
    var picArr = imgData;
    var picSrc;
    for (var i = 0; i < picArr.length; i++) {
  var cur_person = picArr[i];
  if (cur_person.name == name) {
   picSrc = cur_person.src;
  }
 }
 return picSrc;
}

函数执行后将返回该行的src。

var g = getData("p1");
console.log(g);

输出后即可看到结果为:images/p1.jpg