简体   繁体   中英

JavaScript objects returning undefined

I'm sending a http request to an api endpoint which returns the following:

{ "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\\\\"]}\\"" }

I then run following the de-serialize the body of the response:

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

Which gives me this:

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

But when I try to access the individual items of the object, I get undefined .

Example:

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

I'm new to working with json using JavaScript and have in the past used PHP's json_decode() function to process json for back-end projects.

I have done some searching but haven't come across an npm package that is perfect for dealing with json. Can anyone suggest one?

You don't need an additional library. JavaScript's built in JSON will do just fine. Your issue is that the string that gets returned is escaped, so when you do JSON.parse on response.body the result is actually a string .

You could just parse it again: JSON.parse(JSON.parse(response.body)).access_token

However I would look into why the body is being returned as a string. Could be an issue with the API you are using or the http request library. I think the extra string is unnecessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM