Vertisan
Vertisan

Reputation: 738

Foreach on json response

I trying to foreach on my json response.
This is my JSON:

[
    {
        "id":1,
        "firstname":"Erich",
        "sections":[
            "VIP Section",
            "God Section"
        ]
    }
]

So on AJAX success I do:

$.each(data[0].sections[0]  , function(i, star) {
   $('#test-ul').append('<li>' + star + '</li>');
});

But I'm getting error:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in VIP Section

When record has only one section, it's not returning error but too not appends it into HTML.

Upvotes: 1

Views: 3403

Answers (3)

Jeric Cruz
Jeric Cruz

Reputation: 1909

you need to parse the "sections" property since this is an array of strings.

try to use the code below to parse your json result:

 <script>
  var jsonData = [{
                "id": 1,
                "firstname": "Erich",
                "sections": [
                    "VIP Section",
                    "God Section"
                ]
              }];
  function clickIt(){
    console.log(jsonData);

    $.each(jsonData  , function(i, star) {
      console.log("id", star.id);
      console.log("firstname", star.firstname);
      console.log("sections");
      $.each(star.sections, function(i, sectionx){
        console.log(i, '-', sectionx);
      });
    });
  }

</script>

enter image description here

Upvotes: 0

atsituab
atsituab

Reputation: 637

youre trying to access the 0 element in sections which is VIP section and iterate through it. remove [0] from sections

Upvotes: 0

JorgeObregon
JorgeObregon

Reputation: 3320

Seems like you are looping thru the word, not the array.

Try

$.each(data[0].sections  , function(i, star) {
   $('#test-ul').append('<li>' + star + '</li>');
});

Upvotes: 3

Related Questions