Home >Web Front-end >JS Tutorial >How to Properly Handle Newlines in JSON Strings?

How to Properly Handle Newlines in JSON Strings?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-07 20:20:15867browse

How to Properly Handle Newlines in JSON Strings?

Handling Newlines in JSON

In JavaScript, attempting to parse JSON data that contains newlines can lead to errors. This issue arises when using eval() or JSON.parse(), as they interpret newline characters (n) within a quoted string as string termination characters.

Consider the following problematic JSON:

var data = '{"count" : 1, "stack" : "sometext\n\n"}';

Attempting to evaluate this data using eval() or JSON.parse() will result in an "unterminated string literal" error. To resolve this, newlines within quoted strings must be escaped using a double-backslash (").

The correct JSON format would be:

var data = '{"count" : 1, "stack" : "sometext\n\n"}';

By escaping the in the string, it is interpreted as a newline character within the JSON data,而非一个 string 分隔符。此举可让 eval() 和 JSON.parse() 成功解析该 JSON,从而消除先前的错误。

The above is the detailed content of How to Properly Handle Newlines in JSON Strings?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn