最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to distinguish between an actual line break and a n character - Stack Overflow

programmeradmin1浏览0评论

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?

Share Improve this question asked Mar 2 at 7:53 Ashu SahuAshu Sahu 6098 silver badges10 bronze badges 2
  • 4 '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 neither readFileSync nor toString will convert one into the other. – knittl Commented Mar 2 at 7:56
  • 3 What do you think the difference is? \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
Add a comment  | 

1 Answer 1

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(" "));

发布评论

评论列表(0)

  1. 暂无评论