el_pup_le
el_pup_le

Reputation: 12179

Is there something wrong with my json structure?

I'll have my PHP like so:

array(2) {
  [0]=>
  object(stdClass)#20 (1) {
    ["name"]=>
    string(5) "Indie"
  }
  [1]=>
  object(stdClass)#21 (1) {
    ["name"]=>
    string(12) "Cult-classic"
  }
}

Then json_encode it which results in this:

0: {name:Indie}
name: "Indie"
1: {name:Cult-classic}
name: "Cult-classic"

So why is this getting undefined (it's actually just traversing every character treating the structure as a string.

for(var i = 0; i < tagged.length; i++) {
    alert(tagged[i].name);
}

Update:

$.post('/host/tags/item_tags/' + movieId,
    function(tagged) {
        alert(tagged);
        for(var i = 0; i < tagged.length; i++) {
            alert(tagged[i]);
        }
});

Upvotes: 0

Views: 90

Answers (2)

Starx
Starx

Reputation: 79011

Tranverse along the json data with .each() instead

function(tagged) {        
    $.each(tagged, function(k,v) {
       alert(v);
    });
}

Upvotes: 0

Brad
Brad

Reputation: 163313

Somehow, I doubt json_encode() is giving you that kind of broken output. This is the appropriate output:

[
    {"name":"Indie"},
    {"name":"Cult-classic"}
]

So to answer your question, yes, there is something wrong with your output. You can validate your JSON at: http://jsonformatter.curiousconcept.com/

Upvotes: 1

Related Questions