从文件读取后无法访问JSON内容

时间:2014-12-02 12:13:36

标签: jquery json file

我花了几个小时来搜索使用JS读取JSON文件。 我找到的最近的啧啧是https://gist.github.com/zuch/6224600

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]未定义

我无法访问其中的元素。

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

谢谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

看起来你正在努力使这比必要更难。一旦掌握了数据,就可以简单地使用它(虽然我可能会遗漏一些东西):

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

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