Why do I have JSON.stringify before I .parseJSON get the result from the Google+ API?

I just started playing with the Google + API and looked through the docs. It seems pretty straight forward. According to google, calling their API returns json. Why do I need to generate json before parsing json before I call key values ​​in jQuery? Here is an example of the code I'm 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 need to call 20 posts because the "stocks" made by the user are also returned when a "post" request is requested. Then I look at the actual messages in the returned json to only display real messages. The docs also don't seem to tell you how to retrieve data explaining the hierarchy of json objects, so I just needed to track it through the console. 'data.items [i] .object.content' is the content of the google + message.

+4
source share
1 answer

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

You can leave

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

in general, since data already your desired object.

+5
source

Source: https://habr.com/ru/post/1481532/


All Articles