JavaScript 个对象返回未定义

JavaScript objects returning undefined

我正在向 api 端点发送一个 http 请求,其中 returns 以下内容:

{ "status": 200, "headers": "{\"server\":\"nginx\",\"date\":\"Sat, 13 Jun 2015 22:29:35 GMT\",\"content-type\":\"application/json; charset=utf-8\",\"content-length\":\"223\",\"connection\":\"keep-alive\",\"status\":\"200 OK\",\"cache-control\":\"no-cache, no-store, must-revalidate\",\"pragma\":\"no-cache\",\"x-frame-options\":\"SAMEORIGIN\",\"vary\":\"Accept-Encoding\",\"x-ua-compatible\":\"IE=Edge,chrome=1\",\"set-cookie\":[\"_twitch_session_id=4654465464564645645646546; domain=.twitch.tv; path=/; expires=Sun, 14-Jun-2015 10:29:35 GMT; HttpOnly\"],\"x-request-id\":\"lostsOfStringsStuffHere\",\"x-runtime\":\"0.403684\",\"accept-ranges\":\"bytes\",\"x-varnish\":\"1124564703\",\"age\":\"0\",\"via\":\"1.1 varnish\",\"x-mh-cache\":\"rails-varnish-6db1a8; M\",\"front-end-https\":\"on\"}", "body": "\"{\"access_token\":\"lostsOfStringsStuffHere\",\"refresh_token\":\"lostsOfStringsStuffHere\",\"scope\":[\"user_read\"]}\"" }

然后我运行按照反序列化响应的主体:

var response = JSON.parse(response.body);

这给了我这个:

{ "access_token":"lostsOfStringsStuffHere", "refresh_token":"lostsOfStringsStuffHere", "scope":["user_read"] }

但是当我尝试访问对象的各个项目时,我得到 undefined

示例:

console.log(response.access_token); // undefined

我是使用 JavaScript 使用 json 的新手,过去曾使用 PHP 的 json_decode() 函数处理 json后端项目。

我进行了一些搜索,但没有找到适合处理 json 的 npm 包。谁能推荐一个?

您不需要额外的库。 JavaScript 的内置 JSON 就可以了。您的问题是返回的字符串被转义,因此当您在 response.body 上执行 JSON.parse 时,结果实际上是 string.

您可以再次解析它:JSON.parse(JSON.parse(response.body)).access_token

不过,我会调查为什么将正文作为字符串返回。可能是您正在使用的 API 或 http 请求库的问题。我认为多余的字符串是不必要的。