Quick answer
JSON strings cannot contain raw control characters such as a new line, a tab or a carriage return. They must be written as escape sequences: \n, \t and \r. Fix: escape those characters, or let JSON.stringify() do it for you when you build the JSON.
The same error in different languages
- Chrome and Node.js:
Bad control character in string literal in JSON at position N - Firefox:
JSON.parse: bad control character in string literal at line X column Y of the JSON data - Python:
json.decoder.JSONDecodeError: Invalid control character at: line X column Y
Example that fails
The value below is split over two lines in the text itself:
{
"message": "first line
second line"
}
Correct version
{
"message": "first line\nsecond line"
}
Characters that must be escaped inside a string
- New line:
\n - Carriage return:
\r - Tab:
\t - Double quote:
\" - Backslash:
\\ - Any other character below code 32:
\u0000style escape, for example\u001f
How to fix it in code
Do not build JSON by joining strings by hand. Build an object and let the language write the JSON:
const text = "first line\nsecond line";
const json = JSON.stringify({ message: text });
// {"message":"first line\nsecond line"}
In Python, json.dumps() does the same. If you must read JSON that already contains raw control characters, Python can be told to allow them:
import json
data = json.loads(text, strict=False)
JavaScript has no such option, so the text needs to be repaired first.
Fix existing text with Parsekit
Paste the broken JSON into the JSON Repair tool to fix many string problems automatically. To escape or unescape a single text value, use the JSON Escape / Unescape tool. Use the JSON Formatter to find the exact line where parsing fails.
Have broken JSON right now?
Paste it into the free JSON Repair tool. It runs in your browser, so nothing is uploaded.
Open JSON Repair toolFAQ
Can I put a real new line inside a JSON string?
No. The JSON standard does not allow it. Write \n instead.
Why does it happen with text copied from Word or a web page?
Copied text often contains hidden line breaks or tab characters. When pasted into a string, they become raw control characters.
Are line breaks between properties a problem?
No. New lines outside of strings, between properties and values, are normal whitespace and are allowed.