如何读取json数组?

时间:2010-10-26 00:53:27

标签: javascript json

我怎样才能阅读这个json数组?我得到了不确定的结果。我做错了什么?

= jSON file ==

// JSON
{
"items": [
  {
    "title": "welcoem home",
    "author": "Charles Dickens"
  },
  {
    "title": "Harry Potter",
    "author": "J rowling"
  }]
}

<script language="javascript" >
$(document).ready(function() {
  $('#letter-a a').click(function() {
    $.getJSON('q3.json', function(data) {
      $('#dictionary').empty();
      $.each(data, function(entryIndex, entry) {
        var html = '<div class="entry">';
        html += '<h3 class="title">' + entry['title'] + '</h3>';
        html += '<div class="author">' + entry['author'] + '</div>';
        html += '<div class="definition">';
        if (entry['items']) {
          html += '<div class="quote">';
          $.each(entry['items'], function(lineIndex, line) {
            html += '<div class="quote-line">' + line + '</div>';
          });
          if (entry['author']) {
            html += '<div class="quote-author">' + entry['author'] + '</div>';
          }
          html += '</div>';
        }
        html += '</div>';
        html += '</div>';
        $('#dictionary').append(html);
      });
    });
    return false;
  });
});


</script>

<link rel="stylesheet" href="json.css" type="text/css" />
</head>

<body>
<div id="container">
        <div id="header">
        <h2>json stuff</h2>
        </div>

        <div class="letters">
                <div class="letter" id="letter-a">
                <h3><a href="#">A</a></h3>
                </div>      

        </div>
        <div id="dictionary">

        </div>
</div>

1 个答案:

答案 0 :(得分:3)

$.each(data, function(entryIndex, entry) {

您无法在each上运行data,因为它不是数组。我想你想要的是

$.each(data.items, function(entryIndex, entry) {