Reputation: 609
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?
Upvotes: -1
Views: 55
Reputation: 17487
["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(" "));
Upvotes: 1