Undefined results in JavaScript coming from objects

After sending a http request to an api endpoint, I receive the following response:

{ "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 proceed to deserialize the body of this response:

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

The deserialized data looks like this:

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

However, when trying to access individual items within this object, they return as undefined.

For example:

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

Although I have experience with PHP's json_decode(), working with json in JavaScript is new to me. I've searched for npm packages that can aid in handling json but haven't found one that suits my needs. Any recommendations?

Answer №1

Utilizing JavaScript's native JSON functionality is sufficient, no need for an external library. The problem arises from the escaped string that is returned, causing JSON.parse on response.body to result in a string.

To overcome this issue, you can simply parse it twice:

JSON.parse(JSON.parse(response.body)).access_token

It is advisable to investigate why the body is being returned as a string. This could be due to issues with the API or the http request library being used. The extra string seems redundant.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering the issue "SyntaxError: Unexpected token <" when using Shiny and rCharts

This particular query doesn't directly involve JavaScript, however I strongly believe it is at the core of the problem. I possess a dataset containing crime statistics in Seattle. Offense Date Longitude Latitude 3 Assault 2015-10-02 -122.38 ...

Tips on choosing just the selected checkbox values

In my CodeIgniter view, I am utilizing AJAX to post data to my controller. <script type="text/javascript"> $(document).ready(function(){ // find the input fields and apply the time select to them. $('#sample1 inp ...

The input fields seem to be uncooperative, as I am unable to enter

While working on a code, I suddenly found myself unable to type in the input boxes. Despite trying everything, I still can't identify the cause. Below, you'll find all the code I've written since it could be related to anything. On an unrela ...

Tallying the total number of elements within the Item class both pre and post header classes

Hello, I've been brainstorming a JQuery solution to a particular issue. Below, you can see that I have items that come after each heading, which is currently working fine. <div class="header"></div> <div class="item"></div> &l ...

Prevents side-to-side scrolling in the section while enabling scrolling up and down on the

I have a div on my website that allows for horizontal scrolling, while the entire page can be scrolled vertically. When the cursor is over a specific section, it disables vertical scrolling and enables horizontal scrolling within that section. I have imp ...

Introducing the feature of adding an Opacity Slider specifically designed for the chosen object

I am trying to implement an opacity slider to adjust the visibility of selected objects based on the slider's position (100 indicates complete visibility). I am using fabric.js/master/dist/fabric.js and jQuery 3.3.1. Could you please help me identify ...

Exploring the Power of Ajax Integration with Mongodb

I have been trying to figure this out for a while now, but I'm lost. I am attempting to use Ajax to retrieve information from a collection named 'reizen' in MongoDB. My goal is to cycle through all elements within the collection and extract ...

Comparing dates in JavaScript using the built-in Date object

Currently, I am attempting to compare the current date with the one stored in a database using the code snippet below: <script> $("#registerButton").click(function() { var first = $("#scantime").val(); var second = $("#scanbartime").val(); if (parse ...

Testing an Angular service that utilizes $timeout with Jasmine's Mock Clock to ensure accuracy and reliability

Within one of my angular services, I have a function that needs to be called repeatedly at consistent intervals. My approach involves utilizing $timeout in the following manner: var interval = 1000; // Or something var _tick = function () { $timeout ...

Unexpected issue: Ajax success function not displaying anything in the console

My code seems to be running without any output in the console. I am attempting to verify the data in order to trigger specific actions based on whether it is correct or not. However, the if-else conditions are not functioning as expected. Below is a snip ...

What is the best way to extract this function from the methods section of this Vue component?

I recently came across this Vue component called BarChart.vue on https://github.com/apexcharts/vue3-apexcharts Here is the script section of the component; <script> /* eslint-disable */ export default { name: "BarExample", data: funct ...

The React SwiperJs autoplay feature seems to be malfunctioning, as the swiper is not automatically

I have been utilizing the Swiper component in React from this link. However, I encountered an issue with setting it to autoplay as it doesn't auto swipe. Here is my attempted code: // Resource: https://swiperjs.com/get-started/ import React from &apos ...

Locating Advertisements within a Web Page

I am developing an application to identify ads on web pages by using browser automation with Selenium Webdriver and Python. After realizing that many ads are placed within iframes, I created a loop to inspect each frame. browser = webdriver.Chrome() brow ...

The functionality of jQuery on dropdown list change seems to be malfunctioning in Codeigniter

As a novice in CodeIgniter, I've scoured various StackOverflow threads for a solution to my issue without any luck. Below is the view code causing trouble: <select name="select1" id="select1"> <option value="0">None</option> ...

EPERM: unable to perform operation, encountered lstat error during execution of ng build

Encountering an issue with my Angular 4 app when running ng build. Getting the following ERROR: EPERM: operation not permitted, lstat '<dist directory>' Any suggestions or solutions to fix this problem? Thanks in advance! ...

Using Jquery to Extract Information from Google Map Json

Link to Google Maps JSON URL: Click here The JSON data returned is: { "destination_addresses" : [ "100 East Main Street, Edmond, OK 73034, USA" ], "origin_addresses" : [ "2020 East Main Street, Lamar, AR 72846, USA" ], "rows" : [ { ...

Tips for testing views in ember.js using unit tests

We are currently delving into the world of Ember.js. Our development process is completely test-driven, and we aim to apply the same methodology to Ember.js. Having prior experience in test-driven development with Backbone.js apps using Jasmine or Mocha/Ch ...

NPM Error: Module 'balanced-match' Not Found

After updating the node and npm using nvm, I encountered an error when starting the node server. Despite trying various solutions suggested in stack overflow, none seemed to work for me. Below are the steps I tried: 1. Removed node modules and installed t ...

Gathering information from a PHP form without redirecting to a new page

Can an array be passed from JavaScript to PHP on the same page before submission? In my index.php, I have a form where changing the value of an input triggers a function to send the input value to PHP. In PHP, this value is used to make an HTTP request to ...

Employing fetch to send a POST request for inserting data into a JSON server database

I'm currently experimenting with adding new data to my simulated database using JSON server. However, I've encountered an issue where the input information is not being added when I execute the function. Although an ID is generated in my databas ...