pixeline
pixeline

Reputation: 17984

Parsing json issue: object.property is undefined

Here is the json returned by an ajax call:

{
    "StumbleUpon": 0,
    "Reddit": 0,
    "Facebook": {
        "commentsbox_count": 0,
        "click_count": 0,
        "total_count": 0,
        "comment_count": 0,
        "like_count": 0,
        "share_count": 0
    },
    "Delicious": 0,
    "GooglePlusOne": 1,
    "Buzz": 0,
    "Twitter": 1,
    "Diggs": 0,
    "Pinterest": 0,
    "LinkedIn": 1
}

I'm trying to process it in jquery but for some reason that i fail to understand, Facebook.total_count is undefined. I would expect otherwise since the console tells me the above json was received. Moreover, all others (data.Twitter, etc.) work. Here is my callback function where the error is produced. What am i doing wrong?

function(data){

                console.log(data);
//this line throws the error
                var fb = data.Facebook;
                var total = parseInt(data.Twitter + parseInt(fb.total_count) + data.GooglePlusOne + data.Pinterest + data.LinkedIn);
// rest of code.
}

See the code on jsFiddle.

Upvotes: 2

Views: 2792

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

Fundamentally, that code works -- provided that data has already been deserialized. If it hasn't, either...

...add dataType: "JSON" to the ajax call:

$.ajax({
    // ...
    dataType: "JSON",
    // ...
});

...or use $.parseJSON on the result.

function(data) {
    if (typeof data === "string") {
        data = $.parseJSON(data);
    }
    // ...
}

Note: You don't need to use parseInt on those numbers, they're already numbers in the JSON and will be deserialized correctly.

Upvotes: 5

Dpolehonski
Dpolehonski

Reputation: 958

As far as I can see your receieving the JSON as a string but nor parsing it into an actual object. Theres too much on the page to really sift through and tell you accuratly but this seems to be the issue. try jQuery.parseJSON

Upvotes: 0

Related Questions