所以我有一台服务器从Google People api接收有关联系人的数据,我收到的对象具有以下结构:
{ connections:
[ { resourceName: 'people/c3904925882068251400',
etag: '%EgYBAgkLNy4aDQECAwQFBgcICQoLDA0iDFZUOUE0NkRBZW0wPQ==',
names:
[ { metadata: { primary: true, source: [Object] },
displayName: 'Mihai Vrincut',
familyName: 'Vrincut',
givenName: 'Mihai',
displayNameLastFirst: 'Vrincut, Mihai' },
{ metadata: { source: [Object] },
displayName: 'Mihai Vrincut',
familyName: 'Vrincut',
givenName: 'Mihai',
displayNameLastFirst: 'Vrincut, Mihai' } ],
emailAddresses:
[ { metadata: { primary: true, source: [Object] },
value: 'mihai.vrincut@gmail.com' } ] },
{ resourceName: 'people/c3275206487406036814',
etag: '%EgYBAgkLNy4aDQECAwQFBgcICQoLDA0iDHBFVzBUMm8wWU5nPQ==',
names:
[ { metadata: { primary: true, source: [Object] },
displayName: 'aaaaaaaaa',
givenName: 'aaaaaaaaa',
displayNameLastFirst: 'aaaaaaaaa' } ] },
{ resourceName: 'people/c5777943907795350059',
etag: '%EgYBAgkLNy4aDQECAwQFBgcICQoLDA0iDGxOeGYwblg3bFUwPQ==',
names:
[ { metadata: { primary: true, source: [Object] },
displayName: 'costin',
givenName: 'costin',
phoneticFamilyName: 'cancius',
phoneticGivenName: 'costin',
displayNameLastFirst: 'costin' } ],
emailAddresses: [ { metadata: { primary: true, source: [Object] }, value: 'hj' } ],
phoneNumbers:
[ { metadata: { primary: true, source: [Object] },
value: '07543532512',
canonicalForm: '+40754353251' } ] } ], totalPeople: 3}totalItems: 3 }
为了获得这个对象,我使用了util.inspect()方法。但是,当我尝试访问名称时,我得到了未定义:
var response=util.inspect(responses,{depth:5});
Console.log(response.connections[0].names);
有什么问题?
答案 0 :(得分:0)
您应该将响应转换为JSON对象。 试试这个:
console.log(JSON.parse(response).connections[0].names);
(我假设您正在使用Javascript)
答案 1 :(得分:0)
我要做的是验证答案是否为String,你有
console.log (typeof response)
如果是字符串,请将其转换为JSON:
let responseObject = JSON.parse (response);
最后,尝试访问该对象:
console.log (responseObject.connections [0] .names);
你告诉我你的答案:)
答案 2 :(得分:0)
因此,考虑到情况以及您在评论部分提供的信息。 我假设响应已经是一个对象,但util.inspect使它成为一个带有JSON类型语法但在键名称之前和之后没有引号(")的字符串。这就是你获得
的原因{connections:^ SyntaxError:位置2的JSON中出现意外的令牌c
因此,请尝试检查响应对象。
console.log(responses)
获取密钥的名称。和他们一起
console.log(responses.sth.sthElse.anotherSth.anotherSthElse.lastSth.connections)
看看你是否得到了预期的结果:)