JSON Beautifier
Troubleshooting3 min read

Bad Control Character in String Literal in JSON: Fix Raw Newlines and Tabs

Bad control character in string literal, Invalid control character (Python) and '0x0A' is invalid within a JSON string (.NET) all mean a raw newline, tab or other control character sits inside a JSON string. Here is how to escape it.

Escape text for a JSON string

What the error means

Inside a JSON string, the characters U+0000 to U+001F must be escaped. That range includes newline, carriage return and tab. A string that contains an actual line break, rather than the two characters \n, is invalid JSON even though it looks fine in an editor.

Each runtime words it differently. JavaScript (V8): Bad control character in string literal in JSON at position N. Python: Invalid control character at: line L column C. .NET System.Text.Json: '0x0A' is invalid within a JSON string. The string should be correctly escaped. 0x0A is a newline, 0x09 a tab and 0x0D a carriage return.

Invalid and valid
{"note": "line one
line two"}      <- invalid: raw newline inside the string
{"note": "line one\nline two"}     <- valid: escaped as \n

Find the character

Go to the reported position. The invisible character is usually at the end of a line inside a quoted value: a multi-line comment field, an address, a pasted log message or a value copied from a spreadsheet cell.

Paste the document into the validator to see the line and column. Tabs are hard to spot, so search for them explicitly if the position points at what looks like a space.

Fix it at the source: never build JSON by hand

This error almost always comes from code that assembles JSON with string concatenation or a template, so user text goes into the document unescaped. Serialize a real object instead; every JSON library escapes control characters for you.

JavaScript and Python
// Wrong: breaks as soon as comment contains a newline or a quote
const body = `{"comment": "${comment}"}`;

// Right
const body = JSON.stringify({ comment });

# Python
body = json.dumps({"comment": comment})

Reading a file you cannot regenerate

Python's json.loads(text, strict=False) accepts raw control characters inside strings. In JavaScript there is no such option; escape them before parsing, but only inside strings, because newlines between values are legal whitespace.

For a single value, paste the raw text into JSON Escape to get a correctly escaped string you can drop into the document.

JavaScript
// Escape raw control characters that appear inside JSON strings
const fixed = text.replace(/"(?:[^"\\]|\\.)*"/g, s =>
  s.replace(/[\u0000-\u001f]/g, c => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"))
);
const data = JSON.parse(fixed);

Put the example to work

Use your own sample, check the result, and copy or download it. The tool processes your data locally in your browser.

Escape text for a JSON string