I am trying to write a parser for JSON string, but stuck in one test case.
["line // <--- unexpected end of string
break"]
my json file should give this error, similar to vs code, but when my script is trying to parse this, I get a valid JSON object
[ 'line\nbreak' ]
I am reading the file using fs.readFileSync(path).toString('utf-8')
which represents line breaks as \n
. Is there any other way to know if the string contains a \n
character or an actual line break?
How can I distinguish between them and throw an error here?
I am trying to write a parser for JSON string, but stuck in one test case.
["line // <--- unexpected end of string
break"]
my json file should give this error, similar to vs code, but when my script is trying to parse this, I get a valid JSON object
[ 'line\nbreak' ]
I am reading the file using fs.readFileSync(path).toString('utf-8')
which represents line breaks as \n
. Is there any other way to know if the string contains a \n
character or an actual line break?
How can I distinguish between them and throw an error here?
1 Answer
Reset to default 1["line
break"]
is not valid JSON:
JSON.parse('["line\nbreak"]');
Line breaks in strings must be escaped in JSON so that the JSON string contains \
and n
as separate characters:
console.log(JSON.stringify(['line\nbreak']).split("").join(" "));
'new\nline'
is a string comprising 2 lines and a line feed character.'new\\nline'
is a string comprising a single line which contains the two characters backlash and 'n'. The two are very different (1 byte vs 2 bytes) and neitherreadFileSync
nortoString
will convert one into the other. – knittl Commented Mar 2 at 7:56\n
is just an escape sequence for a line break. Basically, if your parse sees a line break while parsing either a property name or a value, it should report and error. I suspect that whatever is showing you the ``n is just doing the escaping for you. – Jon Skeet Commented Mar 2 at 7:56