What could be causing JSON.parse() to not function as intended?

How can it be that this code snippet:

this.store.select(getAuthResponseSelector)
        .subscribe((response: AuthenticateResponse) => {
            if (response != null) {
                console.log('Response', response);
                console.log('ResponseType', typeof response);
                console.log('EntroSubscribeTokenBefore', JSON.parse(JSON.stringify(response)));
                console.log('EntroSubscribeTokenType', typeof JSON.parse(JSON.stringify(response)));
                console.log('EntroSubscribeToken', JSON.parse(JSON.stringify(response)).access_token);
                const newToken = Object.assign({}, response);
                console.log('NewObject', typeof newToken);
                for(let key in newToken){
                    console.log('Key:', newToken[key])
                }
                this.token = newToken.access_token
            }
        });

This is the resulting output:

[12:32:39]  console.log: Response
            {"access_token":"afcddc76-8322-4186-9b54-aa4143f381eb","token_type":"bearer","refresh_token":"fda3fcf4-8335-45cf-94ca-cd0aec1a90cb","expires_in":26313,"scope":"custom
            default","firstname":"testswinetmm_cost","lastname":"testswinetmm_cost","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="562233252225213f3833223b3b093539252216223325223f38313b373f3a7835393b">[email protected]</a>","uid":"testswinetmm_cost"}
[12:32:39]  console.log: ResponseType string
[12:32:39]  console.log: EntroSubscribeTokenBefore
            {"access_token":"afcddc76-8322-4186-9b54-aa4143f381eb","token_type":"bearer","refresh_token":"fda3fcf4-8335-45cf-94ca-cd0aec1a90cb","expires_in":26313,"scope":"custom
            default","firstname":"testswinetmm_cost","lastname":"testswinetmm_cost","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e89c8d9b9c9b9f81868d9c8585b78b879b9ca89c8d9b9c81868f85898184c68b8785">[email protected]</a>","uid":"testswinetmm_cost"}
[12:32:39]  console.log: EntroSubscribeTokenType string
[12:32:39]  console.log: EntroSubscribeToken
[12:32:39]  console.log: NewObject object
[12:32:39]  console.log: Key: {
[12:32:39]  console.log: Key: "
[12:32:39]  console.log: Key: a
[12:32:39]  console.log: Key: c
[12:32:39]  console.log: Key: c
[12:32:39]  console.log: Key: e
[12:32:39]  console.log: Key: s
[12:32:39]  console.log: Key: s
[12:32:39]  console.log: Key: _
[12:32:39]  console.log: Key: t
[12:32:39]  console.log: Key: o
[12:32:39]  console.log: Key: k
[12:32:39]  console.log: Key: e
[12:32:39]  console.log: Key: n
[12:32:39]  console.log: Key: "
[12:32:39]  console.log: Key: :
[12:32:39]  console.log: Key: "
[12:32:39]  console.log: Key: a
[12:32:39]  console.log: Key: f
[12:32:39]  console.log: Key: c
[12:32:39]  console.log: Key: d
[12:32:39]  console.log: Key: d
...

The response object has a custom type, but when trying to convert it into a JSON format, unexpected results are obtained. Can anyone shed light on how this is happening?

UPDATE

Even when attempting to stringify a string which should throw an error, creating a new object with Object.assign() prints out as an object type, yet iterating through its properties displays each letter as a separate string - which seems illogical.

UPDATE 2 I am aware that using JSON.parse(JSON.stringify()) may not make sense in this scenario. I have tried various conversions due to discrepancies between the expected and received responses.

P.S: Although unusual, JSON.parse(JSON.stringify()) is often utilized for generating deep copies of a JSON object :)

Answer №1

The reason for this issue may be that your response variable is being treated as a string instead of an object. When you use JSON.stringify, it converts the string into a JSON format, and then JSON.parse decodes that JSON string back into a regular string.

Update:

Keep in mind that even if you specify response: AuthenticateResponse in TypeScript, there is a possibility that the actual type of response is a string containing JSON data.

Answer №2

It seems that the variable response is a string, so it needs to be parsed with JSON.parse() before it can be used correctly. Currently, you are looping over each character in the string.

Here is what I believe you intended to achieve (note the use of JSON.parse(), and Object.assign() is unnecessary here):

var response = '{"access_token":"afcddc76-8322-4186-9b54-aa4143f381eb","token_type":"bearer","refresh_token":"fda3fcf4-8335-45cf-94ca-cd0aec1a90cb","expires_in":29605,"scope":"custom default","firstname":"testswinetmm_cost","lastname":"testswinetmm_cost","email":"example@email.com","uid":"testswinetmm_cost"}';
const newToken = JSON.parse(response);

for(let key in newToken){
   console.log(key, ":", newToken[key])
}

P.S. The code

JSON.parse(JSON.stringify(response))
in your Console does not make sense. When you parse and stringify at the same time, you end up with the original input because they are opposites. Use parse() for strings to objects and stringify() for objects to strings. Using both simultaneously only adds confusion.

Answer №3

console.log('CheckingSubscribeTokenType', typeof JSON.parse(JSON.stringify(response)));

[11:37:46] console.log: CheckingSubscribeTokenType string

In simpler terms, the output indicates that response is actually a string value.

const json = '{ "name" : "Fred" }';
console.log(typeof json, json);

const jsonToString = JSON.stringify(json);
console.log(typeof jsonToString, jsonToString);

const jsonToStringParsed = JSON.parse(jsonToString);
console.log(typeof jsonToStringParsed, jsonToStringParsed);

console.log("json === jsonToStringParsed", json === jsonToStringParsed);

As such, when attempting to create a new object, you are essentially dealing with a string. Consequently, using Object.assign will yield an unexpected result:

const response = '{ "name" : "Fred" }';

const newToken = Object.assign({}, response);

console.log(typeof newToken);
console.log(newToken);

The created object originates from the string input, hence the key-value pairs represent indexes and associated characters. This transformation occurs because the string primitive is converted into a String object for copying purposes.

const stringObject = new String( '{ "name" : "Fred" }');

console.log("typeof stringObject:", typeof stringObject);
console.log("stringObject instanceof String:", stringObject instanceof String);
console.log(stringObject);

Hence, iterating over newToken involves navigating through an object that represents a String object representation of a string input.

const response = '{ "name" : "Fred" }';

const newToken = Object.assign({}, response);

for (let key in newToken) {
  console.log("key -> value:", key, newToken[key])
}

Furthermore, it's worth noting that Object.assign() does NOT duplicate the String object – instead, it produces a plain object due to the absence of prototype inheritance:

const string = '{ "name" : "Fred" }';
const stringObject = new String(string);

const newTokenFromString = Object.assign({}, string);
const newTokenFromStringObject = Object.assign({}, stringObject);

//false - as it's a string primitive
console.log("string instanceof String:", string instanceof String);
//true
console.log("stringObject instanceof String:", stringObject instanceof String);
//false - denoting an object, not an instance of String
console.log("newTokenFromString instanceof String:", newTokenFromString instanceof String);
//false - representing an object, not an instance of String
console.log("newTokenFromStringObject instanceof String:", newTokenFromStringObject instanceof String);

Answer №4

If you're receiving a response in Object format, you can verify the validity of the JSON data syntax by pasting the response text into an online JSON parser such as JSON Formatter.

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

Establish a connection between two pre-existing tables by utilizing the Sequelize framework

I have two tables already set up (User and PaymentPlan), but they were not initially linked together. PaymentPlan.ts import { DataTypes, Model } from "sequelize"; import { sequelize } from "./DBConnections/SequelizeNewConnection"; exp ...

Adjust the appearance using Timeout within a React component

I am facing a challenge with updating the style in React - specifically, the opacity of a Div element is not updating despite successfully updating the opacity in a timeout event. import React from 'react'; function PortItem(props){ let style ...

JavaScript still mentions a class that no longer exists

One of my elements has a class of .collapsed. When this element is clicked, a jQuery function is triggered to remove the .collapsed class and add the .expanded class instead. Even after the .collapsed class is removed, the function I have created continue ...

Discover local points of interest with the Google Places API integration on your WordPress site through PHP programming

$(document).ready(function() { var image_src = "images/"; var map; var infowindow; var bounds = new google.maps.LatLngBounds(); var PlaceArray = ["restaurant", "cafe", "bar", "grocery_or_supermarket", "parks", "school", "shopping_mall", "movie_t ...

Navigating with the mouse in THREE.js

Big shoutout to the amazing Stack Overflow community for always being there to help budding coders like myself! I've successfully implemented first-person camera movement in my project, allowing me to navigate forward, backward, sideways, and rotate ...

Triggering an automatic pop-up window using JavaScript based on a PHP condition

I have developed a hidden pop-up box that becomes visible when targeted, with its opacity increasing to one. I am aiming for the pop-up to appear if the user is identified as a "firstTimeUser," a status saved in a PHP $_SESSION variable. However, I am stru ...

Searching for JSON array fields in a PostgreSQL database using Rails

Struggling to define a rational scope for my problem. I am trying to extract a list of Model objects with a specific "type" field within a json array column using postgresql. If anyone can guide me in the right direction, that would be helpful. I am open ...

The DIV element only becomes visible after a postback occurs

When I try to hide a DIV tag on the client side and then click submit to postback the data to the server side, the DIV reappears. Is there a way to solve this issue? ...

Having trouble getting the finally clause to work properly in Angular JS version 1.7

In my current project, I am utilizing Angular JS 1.7. Recently, I encountered an issue while using the finally clause within a promise: $http.put( url, null, { headers: { 'Content-Type': 'application/json' } } ).then( ...

Time when the client request was initiated

When an event occurs in the client browser, it triggers a log request to the server. My goal is to obtain the most accurate timestamp for the event. However, we've encountered issues with relying on Javascript as some browsers provide inaccurate times ...

Ways to include new elements in JSON

When handling post service requests, I utilize the following method to parse and update the Database: ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(<String>); UserLogin userLogin = mapper.convertValue(node ...

Vue.js - I am looking to create dynamic buttons that change color when clicked

I have dynamically created buttons using v-for and now I want the clicked button to change color while the others remain the same. <template> <div id="exam-screen" class="exam jumbotron"> <h1>{{ title }}</h1> <div cl ...

Extract every value associated with a particular key using JSON

Is there a way to extract all of the "-temp" values from the provided JSON data? { "weather":{ "notes":{ "cities":[ { "-id":"scranton", "-temp":"17" }, { "-id":"paris", "-temp":"1 ...

Adding information to a pre-existing JSON Array using C#

I am looking to insert additional data into an existing JSON structure For example: { "OrderId":"abc", "products":["a","b","c","etc"] } What is the best way to append more items to the 'products' array? ...

ngFor filter for converting strings to lowercase

In my application, I am implementing a pipes example that converts uppercase strings to lowercase. For example, 'Activities' becomes 'activities'. The data is in Array format, and I am using this filter with *ngFor. However, I am encoun ...

Grouping JSON data in Javascript, such that multiple fields are returned within the parent object

I am currently exploring how to perform a groupBy operation on a JSON file that contains a unique identifier for the field I want to group by. The goal is to return the grouped information as a new object while also preserving some fields from the original ...

Eslint requires that return values are used effectively

I am seeking a TypeScript or ESLint rule that enforces the usage of return values from functions. For example: const getNum = () => 12 This rule should allow me to call the function and store the returned value like this: const a = getNum() However, i ...

Displaying a quasar table with rows sourced from an object of objects stored in the

Encountering an issue with displaying data in my q-table. The problem stems from storing data in the store as an object of objects, whereas q-table requires data to be in the form of an array of objects. Below is the code snippet: store.js import Vue fro ...

Issue with SCSS Syntax in Vue Jest Test runner

I'm having trouble importing and mounting a component in Jest. Unfortunately, I keep getting an error message that says: styles/variables.scss:2 $blue:#324157; ^ SyntaxError: Invalid or unexpected token I've tried a few solutions, but no ...

Exploring the Functionality of POST in AJAX Requests

I'm facing an issue where the data is not displaying on my page even though I am using a Github URL and Ajax POST. Can anyone help me identify what needs to be fixed in the code below? <div id="content"> </div> window.onload = ...