Why JSON.parse() doesn't work as expected

json.parse not working
json.parse array of objects
get value from json object in javascript
json parse python
json.parse unexpected token
json.parse undefined
typescript json parse
json.parse ruby

How is possible that this code:

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
            }
        });

Prints this 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":"testswinetmm_cost@testingmail.com","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":"testswinetmm_cost@testingmail.com","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 have a custom type(an object in any case) but trying to convert it to get a JSON object I get this result, could anybody explain me how is this possible??

UPDATE

Even when stringifiying an string which could make an error. The last part when I create a new object with Object.asssign() I print the type and its tell me that is an object, but when iterating its properties it print each letter as a String, that should not happend I think

UPDATE 2 I also know that JSON.parse(JSON.stringify()) has no sense in this case, I have tried this because based on the response that I expect and what I really recieve doesnt make sense, that is why I was trying various conversions.

P.D: JSON.parse(JSON.stringify()) is not that weird, is commonly used to create deep copy of a JSON object :)


It must be because your response is a string and not an object. So JSON.stringify creates JSON string from string and then JSON.parse parses that JSON string to normal string.

Edit:

You know that even if you use response: AuthenticateResponse in TypeScript, response might not be that type? Your response is clealy type of string containing JSON.

JSON.parse(), The JSON.parse() method parses a string and returns a JavaScript object. The string has to be written in JSON format. The JSON.parse() method can optionally​  why can't JSON.parse() and JSON.stringify() not work. I'm being told by the console that JSON.parse() and JSON.stringify are not recognized functions. Thanks.


It would appear that response is a string and therefore you need to parse it with JSON.parse() before you can use it properly. What is happening now is that you're iterating over a string, and a loop over a string will print each character from the string.

I suspect that something like this is what you really wanted to happen (note the use of JSON.parse(), and also Object.assign() is redundant in this scenario):

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":"testswinetmm_cost@testingmail.com","uid":"testswinetmm_cost"}';
const newToken = JSON.parse(response);

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

JavaScript JSON parse() Method, The JSON object, available in all modern browsers, has two very useful methods to deal with JSON-formatted content: parse and stringify. JSON.parse() takes a  The JSON.parse() function is included in all major browsers and in the latest ECMAScript (JavaScript) standard. The numbers in the table below specifies the first browser version that fully supports the JSON.parse() function:


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

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

This means that response is actually a string.

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);

JSON.parse() and JSON.stringify() ← Alligator.io, parse() takes a JSON string and then transforms it into a JavaScript object. Let's take a look at a code example: JSON.stringify() can take  The JavaScript exceptions thrown by JSON.parse() occur when string failed to be parsed as JSON. Message SyntaxError: JSON.parse: unterminated string literal SyntaxError: JSON.parse: bad control character in string literal SyntaxError: JSON.parse: bad character in string literal SyntaxError: JSON.parse: bad Unicode escape SyntaxError: JSON.parse: bad escape character SyntaxError: JSON.parse: unterminated string SyntaxError: JSON.parse: no number after minus sign SyntaxError: JSON.parse


You are getting response in Object format. To check whether syntax of JSON data is valid or not , you can copy the response text to online JSON parser like JSON Formatter.

How to use JSON.stringify() and JSON.parse() in JavaScript, stringify() with such data types does not throw any error. By the way, as for me, one of the biggest problems of cloning with JSON.stringify() is that  1234as and 123,123 are not valid JSON, and so JSON.parse () throws in both cases. (The former isn't legal JavaScript syntax to begin with, and the latter contains a comma operator that doesn't belong.) 1234 on the other hand is a Number literal and therefore valid JSON, representing itself.


Why JSON.parse(JSON.stringify()) is a bad practice to clone an , Parsing JSON means interpreting the data with whatever language u are using at In javascript to parse the data with JSON.parse(), and the data becomes a  JSON.parse () is used at runtime for data retrieved while the application is running, not for constructing the source code itself.


What does parsing JSON mean?, The standard way to parse JSON in JavaScript is JSON.parse() in an esoteric JavaScript environment that doesn't include the standard APIs. As an empty string is not valid JSON it would be incorrect for JSON.parse('') to return null because "null" is valid JSON. e.g. JSON.parse("null"); returns null. It would be a mistake for invalid JSON to also be parsed to null. While an empty string is not valid JSON two quotes is valid JSON. This is an important distinction.


Parse JSON in JavaScript?, parse() suggests, this method converts a JSON string representation to a JavaScript value (JSON object). It can optionally use a reviver function to perform a  JSON.Parse Syntax Errors In most web applications, nearly all data transferred from a web server is transmitted in a string format. To convert that string into JSON, we use the