我通过Gmail API返回了以下结果。我想知道什么是使用JSON对象的最佳方式。如何引用json的属性
{"result":{"messages":[{"id":"15d862a00074a324","threadId":"15d862a00074a324"},{"id":"15d8628752224d1b","threadId":"15d8628752224d1b"},{"id":"15d8231cfbca0608","threadId":"15d8231cfbca0608"},{"id":"15d812cb47b30f24","threadId":"15d812cb47b30f24"},{"id":"15d5e26548a7fe5b","threadId":"15d5e26548a7fe5b"}],"resultSizeEstimate":5},"body":"{\n \"messages\": [\n {\n \"id\": \"15d862a00074a324\",\n \"threadId\": \"15d862a00074a324\"\n },\n {\n \"id\": \"15d8628752224d1b\",\n \"threadId\": \"15d8628752224d1b\"\n },\n {\n \"id\": \"15d8231cfbca0608\",\n \"threadId\": \"15d8231cfbca0608\"\n },\n {\n \"id\": \"15d812cb47b30f24\",\n \"threadId\": \"15d812cb47b30f24\"\n },\n {\n \"id\": \"15d5e26548a7fe5b\",\n \"threadId\": \"15d5e26548a7fe5b\"\n }\n ],\n \"resultSizeEstimate\": 5\n}\n"}
我是新来的JSON对象,但熟悉PHP对象和数组。我会想引用resultSizeEstimate
并遍历该id。
我试图JSON.stringify(response.resultSizeEstimate);
但没有运气。有人能指出我处理JSON对象的正确方向吗?我似乎找不到任何标准方式。
新增:这是我创造appendpre只是功能输出到一个元素...
function getUnread() {
gapi.client.gmail.users.messages.list({
'userId': 'me',
'q': 'is:unread in:inbox',
}).then(function(response) {
var unread = response;
appendPre(JSON.stringify(response)); // Outputs JSON with string chars \n's
console.log(JSON.parse(response)); // Errors as invalid JSON
});
}
EDITIED功能:下面是引用编辑的工作职能...
function getUnread() {
gapi.client.gmail.users.messages.list({
'userId': 'me',
'q': 'is:unread in:inbox',
}).then(function(response) {
var unread = JSON.parse(JSON.stringify(response));
appendPre(unread.result.resultSizeEstimate);
});
}
JSON.parse给我未捕获的SyntaxError:在位置1的JSON中意外的令牌o ...快速谷歌告诉我我已经在使用json对象。 – Ryan
是的,因为你的json字符串包含无效字符'\ n'例如。 – alexmac
我减少了json字符串,所以现在JSON.parse可以解析它。 – alexmac