April 22, 2012
Is there something wrong with my json structure?
Question by amiawizard
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]);
}
});
Answer by Brad
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/
Answer by Starx
Tranverse along the json data with .each()
instead
function(tagged) {
$.each(tagged, function(k,v) {
alert(v);
});
}