为什么我在.parseJSON之前必须使用JSON.stringify来自Google+ API的结果集?

时间:2020-12-10 15:26:01

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:

我刚刚开始玩google + API并且已经搜索了文档。看起来很简单。根据谷歌,他们的API调用返回json。为什么在调用jQuery中的键值之前,我必须在解析json之前对json进行字符串化?以下是我正在使用的代码示例:

$.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.

注意:我必须拨打20个帖子,因为当出于某种原因请求“post”动词时,用户所做的“份额”也会被返回。然后我在返回的json中查找实际帖子,以便仅显示真实帖子。文档似乎也没有告诉你如何通过解释json对象层次结构来提取数据,所以我只需要通过控制台跟踪它。 'data.items [i] .object.content'是google +帖子的内容。

1 个解决方案

#1


5  

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

您的AJAX调用已经指定了dataType:“json”,因此jQuery已经将返回的JSON解析为JavaScript对象。

You should be able to drop

你应该能够放弃

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

altogether as data already is your desired object.

因为数据已经是您想要的对象。

#1


5  

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

您的AJAX调用已经指定了dataType:“json”,因此jQuery已经将返回的JSON解析为JavaScript对象。

You should be able to drop

你应该能够放弃

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

altogether as data already is your desired object.

因为数据已经是您想要的对象。