2012-12-06 23 views
0

我有一個json文件,我想從中提取數據。當json文件不在數組中時,一切正常。我想問題是我不知道如何在我的.each函數中選擇正確的數據。下面是例子JSON文件:用jQuery顯示json數組。每個

{ 
    "chapter1": [ 
     { 
     "title":"This is the title", 
     "chapter":"1", 
     "verse":"1", 
     "text":"text goes here" 
     }, 
     { 
     "verse":"4", 
     "text":"text goes here" 
     }, 
     { 
     "verse":"6", 
     "text":"text goes here" 
     } 
    ], 

    "chapter2": [ 
     { 
     "title":"This is the title", 
     "chapter":"2", 
     "verse":"1", 
     "text":"text goes here" 
     }, 
     { 
     "verse":"4", 
     "text":"text goes here" 
     }, 
     { 
     "verse":"6", 
     "text":"text goes here" 
     } 
    ] 
} 

這裏是我的循環中顯示的數據:

$.getJSON(passages, function(data) { 
    $.each(data, function() { 
     $('#chapter1 h2').append(this.title); 
     $('#chapter1 h3').append(this.chapter); 
     $('#verses').append('<li><p>' + this.verse + this.text + '</p></li>');  
    }); 
}); 

當我從JSON文件中刪除了「第2章」數據,比一切都運行得很好。我想顯示「chapter1」的內容和「chapter2」的內容。

+0

什麼是你用來創建JSON,因爲它看起來像有一些矛盾有 –

+0

這只是一個.json文件我將一些數據插入。 – user715564

回答

1

出於某種原因,它正在圍繞每個元素的成員創建一個數組。假設這是一致的,您可以訪問titlechapter像這樣:

$("#chapter1 h2").append(this[0].title); 
$("#chapter1 h3").append(this[0].chapter); 

編輯:如果您正在創建的JSON自己,你或許應該改變它的格式是這樣的:

"chapter": { 
    "title": "the title", 
    "chapter": "the chapter", 
    "verses": [ 
     {"verse": "1", "text": "text 1"}, 
     {"verse": "4", "text": "text 2"} 
    ] 
} 

這將在你的問題與$.each工作

+0

所以我重新格式化了你所建議的json數據,現在沒有任何顯示。我是否想改變$ .each語句中的某些內容? – user715564

+0

@ user715564你是什麼意思「什麼都沒有顯示出來?」你有錯誤嗎? –

+0

哈哈這就是我的意思。 $ .each語句中指定的div沒有顯示任何內容。數據未被顯示。我在控制檯中看不到任何錯誤。無論哪種方式,你的第一個建議工作。我可以繼續前進,現在就走這條路,然後再進行格式化。謝謝您的幫助! – user715564

0

json格式不正確,每章json應該看起來像這樣:

"chapter1": { 
     "title":"this is the title", 
     "chapter":"1", 
     "verses":[ 
      { 
      "verse":"1", 
      "text":"some text" 
      }, 
      { 
      "verse":"2", 
      "text":"some other text" 
      }, 
     ] 
    } 

編輯: 你改變你的JSON後,你的代碼看起來應該財產以後這樣的:

$.getJSON(passages, function(data) { 
    $.each(data, function() { 
     $('#chapter1 h2').append(this.title); 
     $('#chapter1 h3').append(this.chapter); 
     $.each(this.verses,function(){ 
      $('#verses').append('<li><p>' + this.verse + this.text + '</p></li>');  
     }); 
    }); 
}); 
+0

儘管我的$ .each語句仍然不起作用?數據不會顯示,並且在控制檯 – user715564

+0

中沒有錯誤,這是因爲您必須更改代碼,以便它也迭代每章章節中的每章章節,您需要每個章節的其他章節 –

+0

噢好了我明白了,謝謝。 – user715564