gpt4 book ai didi

javascript - 将 LinkedIn API 响应正文解析为 JSON

转载 作者:行者123 更新时间:2023-12-03 05:16:58 25 4
gpt4 key购买 nike

这让我抓狂,我希望有人遇到过这种情况并提出一个干净、优雅的解决方案。向 LinkedIn REST Api 发出 JSON 请求时,正文会以带有换行符的字符串形式返回。当我使用 JSON.parse 将字符串解析为 JSON 时,它似乎创建了一个 JSON 对象,但我无法使用点符号使用其相对键来访问这些值。我尝试过转义新行字符、JSON.stringify 然后解析的组合等。我无法让它工作并且它很令人讨厌,尽管我确信有一个我忽略的简单解决方案。以下是 LinkedIn API 的响应:

{"statusCode":200,"body":"{\n \"numConnections\": 152,\n \"numConnectionsCapped\": false\n}","headers":{"server":"Apache-Coyote/1.1","x-li-request-id":"myid","vary":"*","x-li-format":"json","content-type":"application/json;charset=UTF-8","date":"Tue, 10 Jan 2017 00:08:01 GMT","x-li-fabric":"prod-ltx1","transfer-encoding":"chunked","x-li-pop":"prod-ltx1","set-cookie":["lidc=\"b=TB70:g=489:u=129:i=1484006881:t=1484082637:s=AQG3LuLPqWuZiIoHGf2NqD8O7mRfdA4q\"; Expires=Tue, 10 Jan 2017 21:10:37 GMT; domain=.linkedin.com; Path=/"],"x-li-uuid":"53NCd2VAmBSAAWKrrSoAAA=="},"request":{"uri":{"protocol":"https:","slashes":true,"auth":null,"host":"api.linkedin.com","port":443,"hostname":"api.linkedin.com","hash":null,"search":"?format=json","query":"format=json","pathname":"/v1/people/id=myid:(num-connections,num-connections-capped)","path":"/v1/people/id=myid:(num-connections,num-connections-capped)?format=json","href":"https://api.linkedin.com/v1/people/id=myid:(num-connections,num-connections-capped)?format=json"},"method":"GET","headers":{"authorization":"Bearer mytoken"}}}

我正在尝试使用键“numConnections”访问该值,但无法获取该值。

使用 JSON.parse(response.body) 得到这个结果:

{"numConnections":152,"numConnectionsCapped":false}

但是我仍然无法使用访问与每个键关联的值

myObj.numConnections 或我尝试过的任何其他表示法。如何在 NodeJS 中从中获取有效的 JSON 对象?

最佳答案

解析 response.body 的结果是一个对象 - 您可以在其上使用点符号或方括号符号来访问值:

var parsedBody = JSON.parse(response.body);
parsedBody.numConnections //152
parsedBody['numConnections'] //152

关于javascript - 将 LinkedIn API 响应正文解析为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41559249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com