I’m working with some JSON through jQuery, and thought I was doing it correctly, but I keep getting undefined.
If my JSON is organized like so:
{ "item1" : "answer",
"name" : "something",
"title" : "your title",
"favorites" : [ {
"color" : "blue",
"season" : "winter",
"sport" : "baseball"
},
{ ... more favorite objects ... }]
}
Then I call it with
$.getJSON(urlOfMyJSON, null, function(json){
$("p").append(json.item1); // returns 'answer'
$("h3").append(json.favorites); // returns undefined
$("h4").append(json.favorites[0].color); // thought this should work; throws an error because undefined has no "color".
});
Can anyone please point me in the right direction? I know what I want to do, I’m just not quite sure what I’m missing.
Thank you!
There’s nothing wrong with your JSON or the code accessing the properties of the resulting deserialized object. Live example. However, this line:
Doesn’t make much sense. You’re asking jQuery to take this array:
…and append it to all of the
h3elements on your page. jQuery will usetoStringon that, as it’s not a DOM element or jQuery instance, and thetoStringwill presumably come back[object Object]or similar.The next line,
$("h4").append(json.favorites[0].color);, should work fine though, as the live link above demonstrates. Provided there areh4elements on the page for it to update!