jonmrich
jonmrich

Reputation: 4323

Unable to parse some simple JSON

I have no idea what I'm doing wrong here, but I've been at it for a while.

Here's an example of the JSON I get back:

[
    {
        "0": "Horses",
        "1": "Cows",
        "Category": "Animals",
        "total_number": "90"
    }
]

I get this back via AJAX...my success function looks like this:

success: function(data) {
          console.log(data); //this gives me the above JSON
        var tot_num = data.total_number; //this comes back as undefined
 }

Why is that last variable (tot_num) coming back as undefined?

Upvotes: 0

Views: 29

Answers (2)

TimoStaudinger
TimoStaudinger

Reputation: 42460

Because data is actually an array that contains your object at index 0 -- you can see this by the extra brackets [ ... ].

Try this instead:

success: function(data) {
    console.log(data);
    var tot_num = data[0].total_number;
}

Upvotes: 3

epascarello
epascarello

Reputation: 207501

It retunrns undefined because it is an array that is being returned with an object in the first index.

data[0].total_number

Upvotes: 5

Related Questions