Michael Fulton
Michael Fulton

Reputation: 4940

Why does JSON.parse give invalid character

Edit: Solved... I needed to use JSON.stringify() here. Doh.

I am trying to JSON.parse() a response token and keep getting "SyntaxError: Invalid character" in Internet Explorer. (Not sure if this issue is present in Chrome due to CORS, but that's a different issue.)

console.log(response.token.isAdmin)
// false

console.log(JSON.parse(response.token.isAdmin))
// false

console.log(response.token.tokenValue)
// 36151b9e-ad0d-49de-a14b-5461489c7065

console.log(JSON.parse(response.token.tokenValue.toString()))
// SyntaxError: Invalid character

The same error occurs for any string I am trying to parse. If the source is not a string (boolean, integer) the parsing works fine.

Why isn't this working and how can I put my object into a string?

Upvotes: 0

Views: 13641

Answers (2)

Oriol
Oriol

Reputation: 288120

36151b9e-ad0d-49de-a14b-5461489c7065 is invalid JSON.

JSON.parse('36151b9e-ad0d-49de-a14b-5461489c7065'); // SyntaxError

Maybe you meant "36151b9e-ad0d-49de-a14b-5461489c7065", which is valid JSON.

JSON.parse('"36151b9e-ad0d-49de-a14b-5461489c7065"');
// 36151b9e-ad0d-49de-a14b-5461489c7065

Or maybe you wanted to stringify to JSON instead of parse

JSON.stringify('36151b9e-ad0d-49de-a14b-5461489c7065');
// "36151b9e-ad0d-49de-a14b-5461489c7065"

Upvotes: 5

Travis
Travis

Reputation: 12379

It appears that you are trying to parse a string that is not valid JSON.

You could parse a string like this:

var parseMe = '{ "tokenValue": "36151b9e-ad0d-49de-a14b-5461489c7065" }';
var parsed = JSON.parse(parseMe);

// parsed is now equal to Object {tokenValue: "36151b9e-ad0d-49de-a14b-5461489c7065"}

But you cannot parse something that is not formatted as JSON, like this:

var parseMe = '36151b9e-ad0d-49de-a14b-5461489c7065';
var parsed = JSON.parse(parseMe);

// Uncaught SyntaxError: Unexpected token b in JSON at position 5

If instead you wanted to get a JSON object parsed as a string, you could use JSON.stringify() like so:

var stringifyMe = { tokenValue: '36151b9e-ad0d-49de-a14b-5461489c7065' };
var stringified = JSON.stringify(stringifyMe);

// stringified is now equal to the string {"tokenValue":"36151b9e-ad0d-49de-a14b-5461489c7065"}

Upvotes: 1

Related Questions