2014-12-02 41 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