Fix bad control character errors in JSON

What "bad control character in string literal" means in JSON, how to find the character at the reported position, and how to fix it without losing data.

The error "Bad control character in string literal" means a JSON parser found a raw control character inside a quoted string. Usually it is a line break, carriage return or tab. JSON requires these characters to be escaped. The reliable fix is to escape them where the JSON is produced. Deleting them after the fact is usually the wrong move.

What the error means

The JSON standard (RFC 8259) requires every character from U+0000 to U+001F to be escaped inside strings. That range includes the line feed, the carriage return, the tab, the form feed and the null byte. Outside strings, space, tab, line feed and carriage return are allowed as whitespace between tokens. That is why a pretty-printed file with many line breaks can be valid, while a single unescaped line break inside a value is not. DEL (U+007F) and characters above U+001F do not have to be escaped.

The wording of the error varies by parser and version, so treat it as a pattern rather than an exact string:
• Chromium-based browsers and Node.js report a bad control character "in JSON at position" followed by a number.
• Firefox reports a similar message with a line and column.
• Python's json module raises an "Invalid control character" error with line, column and char values.

In JavaScript, the position is a zero-based offset into the text passed to the parser. It identifies the character where parsing failed. JavaScript counts offsets in UTF-16 code units, so an emoji outside the Basic Multilingual Plane counts as two. As a result, the offset may not match the column an editor shows, because editors may count code points or visible characters instead.

What escaping changes and what it does not

Escaping changes the stored JSON text but not the value it represents. A raw line break becomes two characters, a backslash followed by n. Once the JSON is parsed, the value contains a real line break again. The round trip is lossless. Stripping control characters or replacing them with spaces is different: it changes the data itself.

This invalid example has a raw line break inside the value:

{"note":"line one
line two"}

The valid version escapes the line break:

{"note":"line one\nline two"}

Counting from zero, the line break in the invalid example sits at offset 17. A parser that reports offsets should point to that character.

Character | Code point | JSON escape
Line feed | U+000A | \n
Carriage return | U+000D | \r
Tab | U+0009 | \t
Backspace | U+0008 | \b
Form feed | U+000C | \f
Any other control character, such as null or escape | U+0000 to U+001F | \u followed by four hex digits, for example \u0000 or \u001b

Visual text transformations are a separate issue and do not trigger this error. Reversed text, mirrored glyphs, styled Unicode "fonts" and bidirectional marks such as U+200E or U+202E all use characters above U+001F, which JSON allows unescaped. Such characters can make a string look different from what it stores, but they will not cause this error. One related trap: reversing the serialized JSON text instead of the parsed value can split escape sequences apart. That produces a different syntax error, not this one.

Why it happens and how to tell the causes apart

Start by finding the actual character at the reported position. Its character code usually points straight to the cause.

// JavaScript
const pos = 17; // offset from the error message
console.log(text.charCodeAt(pos)); // 10 = line feed, 13 = carriage return, 9 = tab, 0 = null, 27 = escape
console.log(JSON.stringify(text.slice(Math.max(0, pos - 20), pos + 20)));
# Python (the "char" value counts code points)
pos = 17
print(ord(text[pos]))
print(repr(text[max(0, pos - 20):pos + 20]))

Both snippets print the surrounding text with control characters shown as escapes, so invisible characters become visible. With the character identified, match it against these plausible causes:

  • JSON built by string concatenation or templates: inserted values that contain line breaks or tabs end up raw inside strings. Check whether code assembles the JSON as text. Fix it by building a data structure and serializing it with JSON.stringify or json.dumps.
  • An escape consumed by a source-code string literal: in JavaScript or Python, writing \n inside an ordinary string literal creates a real line break before the JSON parser ever sees the text. Check whether the JSON is written inline in code. Fix it by doubling the backslash, using a raw string, or serializing an object instead.
  • Pasted or hand-edited content: multi-line text pasted into a JSON value, or tabs copied from spreadsheets and documents. Check for codes 10, 13 or 9 at the reported position.
  • Windows line endings: carriage returns (code 13) left inside values when content was assembled from text files.
  • Terminal color codes: output captured from a command-line tool may contain the escape character (code 27). Fix it by disabling colored output in the producing command, or by stripping the escape sequences before embedding the text.
  • Wrong text encoding: repeated null characters (code 0) at regular intervals suggest the file was decoded with the wrong encoding, for example UTF-16 read as a single-byte encoding. This is a suspected cause, not a confirmed one. Verify the file's actual encoding before re-reading it.
// The JavaScript literal turns \n into a real line break before JSON.parse runs
JSON.parse('{"a":"x\ny"}');                 // throws
JSON.parse('{"a":"x\\ny"}');                // parses; the value contains a line break
JSON.parse(JSON.stringify({ a: "x\ny" }));  // safest: let the serializer escape

Repairing JSON you did not produce

Fixing the producer is always the better option. When that is not possible, there are two targeted repairs.

The first is Python's tolerant mode. The json module documents a strict=False option that accepts control characters inside strings. The parsed values keep the raw characters. Other parsers will still reject the original text, so re-serialize the data before passing it on.

import json
data = json.loads(text, strict=False)  # accepts raw control characters inside strings
clean = json.dumps(data)               # re-serialized with proper escapes

The second is escaping control characters only inside string literals. A global search-and-replace of line breaks does not work. It also changes the whitespace between tokens, and a backslash sequence outside a string is itself invalid. A small scanner that tracks whether it is inside a string avoids that problem:

function escapeControlCharsInStrings(text) {
  let out = "";
  let inString = false;
  let escaped = false;
  for (const ch of text) {
    const code = ch.charCodeAt(0);
    if (inString) {
      if (escaped) {
        escaped = false;
      } else if (ch === "\\") {
        escaped = true;
      } else if (ch === '"') {
        inString = false;
      } else if (code < 0x20) {
        out += "\\u" + code.toString(16).padStart(4, "0");
        continue;
      }
    } else if (ch === '"') {
      inString = true;
    }
    out += ch;
  }
  return out;
}

The scanner assumes the rest of the document is well formed. It will not repair unescaped quotation marks or other structural damage. The \u form it writes parses to the same characters as the short escapes, so no data is lost. Stripping characters instead is lossy and is appropriate only when they are noise, such as terminal color codes or stray nulls from a decoding mistake.

Readability and usability after copying or sharing

Escaped JSON is valid but harder for people to read. Multi-line text appears on one line with \n sequences in place of line breaks. Screen readers, search tools and editors work on the text as stored. In raw JSON they meet a backslash and a letter, not a line break, and the real breaks return only after an application parses and displays the value. This describes what the text contains; no specific assistive technology was tested for this article.

Copying and pasting is a common way the error comes back. A debugging console may display a parsed string with real line breaks; copying that display back into a JSON file reintroduces raw control characters. Rich-text sources can add tabs or other invisible characters. Pasting JSON through chat apps, email or word processors can also convert straight quotes to curly ones or wrap lines. Those changes cause different syntax errors, and no named destination was tested here.

Plain text is often a better fit when the content is long prose that people edit by hand. Keeping it in a plain-text or Markdown file is easier than maintaining escape sequences inside JSON. A format with native multi-line strings is another option. For machine-to-machine exchange, escaped JSON produced by a serializer remains the right choice.

Recommendation

Escaping control characters is the right fix for this error. It is lossless and every standards-compliant parser accepts the result. The tradeoff is that the raw JSON becomes harder for humans to read and edit. Generate JSON with a serializer rather than by assembling strings. Use tolerant parsing or a string-aware scanner only for input you cannot control, and re-serialize the result afterward. Strip characters only when you have confirmed they carry no meaning.

Limits of this article

No specific JSON formatter, validator or online repair tool was tested. Their handling of control characters, and their privacy or data retention practices, are not assessed here and cannot be judged from how a tool looks. If the data is sensitive, use a local parser or check the tool's documented policy. The exact error wording across engine versions was not verified for this article, and no measurements are reported.