2012-12-06 25 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