2011-06-19 32 views
0

讀取JSON數據我有一個JSON文件:使用的getJSON

{ 
    "bible" : { 
    "@attributes" : { 
     "translation" : "ASV" 
    }, 
    "testament" : [ 
     { 
     "@attributes" : { 
      "name" : "Old" 
     }, 
     "book" : [ 
      { 
      "@attributes" : { 
       "name" : "Genesis" 
      } 
      }, 
      { 
      "@attributes" : { 
       "name" : "Exodus" 
      } 
      }, 
      { 
      "@attributes" : { 
       "name" : "Leviticus" 
      } 
      }, 
      { 
      "@attributes" : { 
       "name" : "Numbers" 
      } 
      }, 
      { 
      "@attributes" : { 
       "name" : "Deuteronomy" 
      } 
      }, 
      { 
      "@attributes" : { 
       "name" : "Joshua" 
      } 
      }, 
      { 
      "@attributes" : { 
       "name" : "Judges" 
      } 
      }, 
      { 
      "@attributes" : { 
       "name" : "Ruth" 
      } 
      } 
     ] 
     } 
    ] 
    } 
} 

我使用代碼來閱讀:

$(document).ready(function(){ 
    $.getJSON("asv/index.json", function(json) { 
     alert("JSON Data: " + json.bible.testament[1].name); 
    }); 
}); 

但是這給了我不確定。請讓我知道如何閱讀書名。還@attributes是什麼? 謝謝

回答

0

您的數據有錯誤的對象路徑。我建議您將json數據粘貼到查看器中,以便更容易地查看您需要獲取的內容。例如,嘗試http://jsonviewer.stack.hu/

<script type="text/javascript"> 
$(document).ready(function(){ 
    $.getJSON("asv/index.json", function(json) { 
     alert(json.bible.testament[0]['@attributes'].name); 
     alert(json.bible.testament[0].book[0]['@attributes'].name); 
    }); 
}); 
</script> 

這對我很有用。請注意,您沒有任何testament[1]索引,只有testament[0]

@attributes部分似乎是生成JSON的腳本正在創建的東西,根本沒有必要使用JSON。如果我可以訪問創建JSON的腳本,我會刪除它,但也許它在某些您看不到的系統中使用。

0

json.bible.testament[1].name未定義。

嘗試json.bible.testament[1]['@attributes'].name

0

如果您有支持的console.log一個瀏覽器(Firefox爲例),你可以做一個「的console.log(JSON)」,並期待在結構。
您可以像訪問名稱:

json.bible.testament [0] .book [0] [ '@屬性']命名
json.bible.testament [0] .book [1] [ '@屬性']命名
...

2

試試這個:

$.getJSON('asv/index.json', 
function(json) { 
    $.each(json.bible.testament[0].book, // $.each() looping on each books 
    function(i, value) { 
     console.log(value['@attributes'].name); // here you get the name of books 
    });