Friday, February 23, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  191] [ 3]  / answers: 1 / hits: 29826  / 9 Years ago, thu, april 16, 2015, 12:00:00

Why can't you parse a json with a n character in javascript



JSON.parse('{x: n}')



However when you do JSON.parse(JSON.stringify({x : n})), it is valid.



http://www.jslint.com/ says that {x: n} is a valid JSON. I wonder what does spec says about this?



Update:
For those who marked this duplicate, this is not the same question as How to handle newlines in JSON. This question is more about why can't an unescaped newline character allowed in JSON.


More From » json

 Answers
17

JSON.parse('{x: n}') fails because '{x: n}' is not a valid JSON string due to the unescaped slash symbol.



JSON.parse() requires a valid JSON string to work.



'{x: \n}' is a valid JSON string as the slash is now escaped, so JSON.parse('{x: \n}') will work.



JSON.parse(JSON.stringify({x : n})) works because JSON.stringify internally escapes the slash character.



The result of JSON.stringify({x : n}) is {x:n} but if you try to parse this using JSON.parse('{x:n})' it will FAIL, as it is not escaped. As JSON.stringify returns an escaped character, JSON.parse(JSON.stringify()) will work.


[#67050] Tuesday, April 14, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maxinec

Total Points: 117
Total Questions: 116
Total Answers: 116

Location: Bangladesh
Member since Sat, Jan 23, 2021
3 Years ago
maxinec questions
;