Connor
Connor

Reputation: 4168

JSON object accessor returning undefined

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!

Upvotes: 0

Views: 907

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

There's nothing wrong with your JSON or the code accessing the properties of the resulting deserialized object. Live example. However, this line:

$("h3").append(json.favorites);

Doesn't make much sense. You're asking jQuery to take this array:

[
    { 
        "color" : "blue",
        "season" : "winter",
        "sport" : "baseball"
    }
]

...and append it to all of the h3 elements on your page. jQuery will use toString on that, as it's not a DOM element or jQuery instance, and the toString will 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 are h4 elements on the page for it to update!

Upvotes: 1

Itay Moav -Malimovka
Itay Moav -Malimovka

Reputation: 53597

do that to see the problem:

$.getJSON(urlOfMyJSON, null, function(json){
   alert(json.toSource());
});

Upvotes: 1

Related Questions