user715564
user715564

Reputation: 1690

Displaying json arrays with jQuery .each

I have a json file that I want to pull data from. When the json file is not in an array than everything works just fine. I guess the problem is that I do not know how to select the correct data in my .each function. Here is the example json file:

{
   "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"
      }
   ]
}

Here is my loop to display the data:

$.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>');    
    });
});

When I remove the "chapter2" data from the json file, than everything works just fine. I would like to display the "chapter1" contents and the "chapter2" contents.

Upvotes: 0

Views: 1387

Answers (2)

Marcelo Biffara
Marcelo Biffara

Reputation: 831

the json is malformed, json for each chapter should look something like this:

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

EDIT: After you change your JSON, you code should look somthing like this:

$.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>');     
        });
    });
});

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191819

For some reason, it's creating an array around members of each element. Assuming this is consistent, you can access title and chapter like so:

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

EDIT: If you are creating the JSON yourself you should probably change its format to something like this:

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

This will work with the $.each in your question

Upvotes: 1

Related Questions