5

I just started playing around with the google+ API and have scoured the docs. It seems pretty straight forward. According to google, a call on their API returns json. Why then do I have to stringify the json before parsing the json before I call key values in jQuery? Here is the sample of code I am working with:

$.ajax({
    url: "https://www.googleapis.com/plus/v1/people/{user number}/activities/public?key={my api key}",
    data: {
        "maxResults": 20,
        "verb": "post"
    },
    dataType: "json",
    type: "get",
    success: function (data) {
        var num_actual_posts = 0;
        data = $.parseJSON(JSON.stringify(data));
        var listElements = $('ul#googleFeedUL li');

        for (var i = 0; i < data.items.length; i++) {
            if (data.items[i].verb == "post") {
                $(listElements[num_actual_posts]).append(data.items[i].object.content);
                num_actual_posts++;
                if (num_actual_posts > 5) {
                    break;
                }
            }
        }
    },
    error: function (e) {
        alert(e);
    }
});

NOTE: I have to call 20 posts, because "shares" made by user also get returned when "post" verb is requested for some reason. I then look for actual posts within the returned json in order to display only real posts. The docs also don't seem to tell you how to extract data by explaining the json object hierarchy, so I just had to track it down through the console. 'data.items[i].object.content' is the content of a google+ post.

2
  • Yeah that looks strange! You shouldn't have to do that i guess.
    – techfoobar
    Commented May 18, 2013 at 16:14
  • What happens if you comment out that line: data = $.parseJSON(JSON.stringify(data)); ?
    – techfoobar
    Commented May 18, 2013 at 16:15

1 Answer 1

5

Your AJAX call already specifies dataType: "json", so jQuery will already parse the returned JSON to a JavaScript object.

You should be able to drop

data = $.parseJSON(JSON.stringify(data));

altogether as data already is your desired object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.