tags:

views:

53

answers:

1

How can I read this json array? I am getting undefined results. What am I doing wrong?

= 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>
+3  A: 
$.each(data, function(entryIndex, entry) {

You can't run each on data as it is not an array. I think what you want is

$.each(data.items, function(entryIndex, entry) {
Phil Brown
thanks. that worked. is there any other way of doign this without using jquery? -thanks
You could use just about any other library / framework or write out all the code yourself in pure JavaScript.
Phil Brown
how would u read this using plain javascript?
Ignoring the AJAX fetching part, to iterate over the items, you would use `for (var i = 0; i < data.items.length; i++) { var item = data.items[i]; ... }`
Phil Brown