Home >Web Front-end >JS Tutorial >How to Properly Encode Newlines in JSON Strings to Avoid Parsing Errors?
When handling JSON in JavaScript, newlines can pose a challenge during the parsing process. Parsing errors may arise if newlines are not appropriately encoded within JSON strings.
In the provided code snippet, the error occurs because the newline character (n) is not correctly handled within the JSON string. When attempting to use eval('(' data ')') to parse the JSON, the newline causes the string to be terminated prematurely, resulting in an "unterminated string literal" error. Similarly, using JSON.parse(data) leads to similar errors due to the unexpected newline token.
To resolve this issue, the newline character must be escaped using a double-backslash (\). Here's the corrected JSON string:
var data = '{"count" : 1, "stack" : "sometext\n\n"}';
By escaping the , you instruct the JSON parser to interpret it as part of the string value rather than a literal newline character. This allows the JSON to be parsed successfully without causing any errors.
The above is the detailed content of How to Properly Encode Newlines in JSON Strings to Avoid Parsing Errors?. For more information, please follow other related articles on the PHP Chinese website!