0

Hello I am wondering why this line doesn't work:

JSON.parse({"a":"\u00A9"})
I tried to serach in MDN website but I didn't find anything referring to in json.parse

Unicode escaping is syntactically legal in js according to this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals

What is the problem and how can I safely parse text with JSON.parse

1 Answer 1

2

{"a":"\u00A9"} is a JavaScript object literal.

JSON.parse expects to be passed a string so it is implicitly converted to a string ("[object Object]").

The [ is fine, because a JSON text can start with an array.

The o is then an error because it isn't allowed there.


A literal copyright symbol (remember that \u00A9 inside a JavaScript string literal will be consumed by the JS parser before it gets to the JSON parser) or the unicode escape sequence would be fine.

console.log(JSON.parse('{"a":"\u00A9"}')); console.log(JSON.parse('{"a":"\\u00A9"}'));


Note that creating a string literal in JS source code that contains JSON and then parsing it is a terrible idea. You have to deal with nested levels of escaping, and it is inefficient.

If you have an object: use the object.

var data = {"a":"\u00A9"}; console.log(data.a);

Sign up to request clarification or add additional context in comments.

3 Comments

How could I parse the object literal? Should I stringify it first? Would you recommend something for "safe parsing", Thanks a lot for your answer it is really helpful
Ok u added code will check it and mark solution if ok
If you have an object literal then just use the object. Converting it to JSON is pointless unless you want to export it out of JS.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.