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.
Fundamentally, that code works — provided that
datahas already been deserialized. If it hasn’t, either……add
dataType: "JSON"to theajaxcall:…or use
$.parseJSONon the result.Note: You don’t need to use
parseInton those numbers, they’re already numbers in the JSON and will be deserialized correctly.