1

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.

3
  • 1
    Any reason you can't have parsing JSON in the first place? Commented Nov 28, 2015 at 17:05
  • Why not just write { notation: 'fixed', precision: 2 } as a JavaScript object literal? Commented Nov 28, 2015 at 17:07
  • The reason why I can't parse a JSON string to begin with is because I can't allow it in the options-string that I wish to parse. Those curly brackets are already parsed as something else, so they're are not available in the string so as to stuff JSON inside. Commented Nov 30, 2015 at 8:34

2 Answers 2

3

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"';
Sign up to request clarification or add additional context in comments.

3 Comments

2 doesn't necessarily need to be in quotes.
@Andy you are right. Boolean and integers don't really need quotes.
Actually, I never knew or expected that keys in json need quotes. I see how that makes them safter (keywords), but I didn't think it was a requirement. As for which quotes, this also fails: >> var text = 'notation: "fixed", precision: 2'; JSON.parse("{" + text + "}"); <<
1

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

1 Comment

Thanks, perfect. I made it even a little more fail-proof using >> text.replace(/[\'\"]/g, '"') << so that it can be both single and double quotes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.