tobibeer
tobibeer

Reputation: 500

JSON.parse — "unexpected token" with constructed JSON string

This throws: "Uncaught SyntaxError: Unexpected token n(…)" ...

var text = "notation: 'fixed', precision: 2";
JSON.parse("{" + text + "}");

No clue as to why or how to safely parse.

Upvotes: 1

Views: 630

Answers (2)

Oleksandr T.
Oleksandr T.

Reputation: 77482

You have wrong JSON, you should wrap keys to double quotes, like this

var text = "notation: 'fixed', precision: 2";
text = text.replace(/\'/g, '"').replace(/(\w+):/g, '"$1":');
console.log( JSON.parse("{" + text + "}") );

Upvotes: 1

Moin
Moin

Reputation: 1143

You should have tried a linter first.

The problem is that you are using single quote for key/value in your text or not using at all.

Your text should be:

var text = '"notation": "fixed", "precision": "2"';

Upvotes: 3

Related Questions