2014-12-02 46 views
0

我花了数小时寻找使用JS读取JSON文件。 我发现的最接近的是这https://gist.github.com/zuch/6224600从文件中读取后无法访问JSON内容

cells.json:

{ 
    "cells": [ 
    { 
     "img": "img/singlestitch_thumb.jpg", 
     "url": "http://www.google.com", 
     "description": "an interactive 'kite' sketch based on a favorite letter[requires java]", 
     "smallwin": true 
    }, 
    { 
     "img": "img/text3d_thumb2.jpg", 
     "url": "http://www.yahoo.com", 
     "description": "animated custom font design in 3d (featured on the 'processing' site)[requires java]", 
     "smallwin": true 
    }, 
    { 
     "img": "img/jazzer_thumb.jpg", 
     "url": "http://flickr.com", 
     "description": "a 3d musician that 'plays along' with arbitrary audio tracks[req. javajsyn]", 
     "smallwin": true 
    } 
    ] 
} 

testjson.html:

var cells = []; 

$.getJSON("cells.json", function(json) { 

    $.each(json, function(i, lv_1) { 

     $.each(lv_1, function(j, lv_2) { 

      $.each(lv_2, function(k, lv_3) { 
       //console.log(k + ':' + lv_3 + ''); 
       //console.log(JSON.parse(k + ':' + lv_3 + '')); 
       cells.push(k + ':' + lv_3 + ''); 
      }); 
     }); 
    }); 
}); 

console.log(cells); 

这是错误。

console.log(cells[0].url); // TypeError: cells[0] is undefined

我无法访问其中的元素。

附件是zip文件包。您可以使用Firefox或设置本地服务器进行测试。 https://www.dropbox.com/s/nmfq98s7raep92r/json%20test.zip?dl=0

谢谢!

回答

0

好像你正在这不是必要的要困难得多。一旦你的数据,你可以简单地使用它(虽然也许我失去了一些东西):

$.getJSON("cells.json", function (json) { 

    var cells = json.cells; 
    console.log(cells[0].url); 
}); 
0

首先,你的JSON只有2个级别,所以第三个each将会失败。其次,你的第一个循环应该使用json.cells。试试这个:

$.getJSON("cells.json", function (json) { 
    $.each(json.cells, function (i, lv_1) { 
     $.each(lv_1, function (j, lv_2) { 
      cells.push(j + ':' + lv_2 + ''); 
     }); 
    }); 
}); 

Example fiddle

+0

http://jsfiddle.net/Lnjg57t8/错误:未定义 – 2014-12-02 12:28:30

+0

这是从来没有去上班的你创建一个数组,而不是一个对象。如果你想要一个对象,你需要彻底改变你的逻辑 – 2014-12-02 12:28:52

+0

谢谢!有没有教程呢?或者什么是阅读它的最佳方式?我只想读第一个'url',第一个'img',然后是第二个,等等。 – 2014-12-02 12:30:26