【发布时间】:2015-06-13 22:50:51
【问题描述】:
我正在向 api 端点发送一个 http 请求,该端点返回以下内容:
{ “状态”:200, "headers": "{\"server\":\"nginx\",\"date\":\"2015 年 6 月 13 日星期六 22:29:35 GMT\",\"content-type\":\"应用程序/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;域=.twitch.tv;路径=/;过期=周日,2015 年 6 月 14 日 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\",\"前端-https\":\"on\"}", "body": "\"{\\"access_token\\":\\"lostsOfStringsStuffHere\\",\\"refresh_token\\":\\"lostsOfStringsStuffHere\\",\\"scope\\":[\ \"user_read\\"]}\"" }
然后我按照响应主体的反序列化运行:
var response = JSON.parse(response.body);
这给了我这个:
{ "access_token":"lostsOfStringsStuffHere", "refresh_token":"lostsOfStringsStuffHere", “范围”:[“user_read”] }
但是当我尝试访问对象的各个项目时,我得到了undefined。
例子:
console.log(response.access_token); // undefined
我是使用 JavaScript 处理 json 的新手,过去曾使用 PHP 的 json_decode() 函数为后端项目处理 json。
我进行了一些搜索,但还没有找到一个非常适合处理 json 的 npm 包。谁能推荐一个?
【问题讨论】:
-
你真的想在那个 JSON 上使用 jsonlint.com
-
能否展示发送请求的代码,也许我们可以找出为什么它会以字符串而不是 JSON 的形式返回。
-
@MarkEriksson 我正在使用Sails.js,它提供了一种简单的重定向方法:
return res.redirect('url');。
标签: javascript json npm