# Control character in JSON: what “Bad control character in string literal” means and how to fix it

> Fix “Bad control character in string literal” in JSON: which characters must be escaped, what each parser reports and how to escape them.

- URL: https://jsonstatham.dev/errors/control-character/
- Language: English (en)
- Russian version: https://jsonstatham.dev/ru/errors/control-character.md
- Updated: 2026-11-08

A line break pressed as Enter inside a string. JSON wants it written as `\n`, not typed. Every character from U+0000 to U+001F (line feed, carriage return, tab and the rest) has to be escaped inside a JSON string, and a raw one stops the parser.

## A raw line break inside a JSON string

This document looks harmless and fails everywhere. The string value contains a real line break, not the two characters `\` and `n`:

```json
{"msg":"line one
line two"}
```

The valid version keeps the whole string on one line and writes the break as an escape. The value is the same two lines of text once parsed:

```json
{"msg":"line one\nline two"}
```

The usual suspects are tabs pasted from a spreadsheet, `\r` from Windows text, colour codes from terminal logs (they start with U+001B, escape) and, most of all, JSON assembled by gluing strings together instead of using a serializer.

## Why JSON requires escaping control characters (RFC 8259)

[RFC 8259, section 7](https://www.rfc-editor.org/rfc/rfc8259#section-7) lets almost any character stand in a string as it is. The exceptions are the quotation mark, the backslash “and the control characters (U+0000 through U+001F)”. The grammar spells it out: an unescaped character must be in one of these ranges, and `%x00-1F` is in none of them.

```text
unescaped = %x20-21 / %x23-5B / %x5D-10FFFF
```

Five control characters have short escapes: `\b`, `\f`, `\n`, `\r`, `\t`. Any other is written as `\u` with four hex digits, for example `\u001b`. The delete character (U+007F) and the Unicode line separators U+2028 and U+2029 are not in the forbidden range: JSON accepts them raw.

## Bad control character messages by parser

Input: the bad example above, with the line break at character index 16. Each message was produced by running that parser on 2026-11-08 (Firefox: from the SpiderMonkey source). The third column is the switch that makes the parser accept raw control characters, where one exists.

| Parser | Message | Lenient option |
| --- | --- | --- |
| Chrome 156, Node 24–25 (V8) | `Bad control character in string literal in JSON at position 16 (line 1 column 17)` | None |
| Firefox (SpiderMonkey) | `bad control character in string literal` | None |
| Safari 27 (JavaScriptCore) | `JSON Parse error: Unterminated string` | None; the message is misleading, the string does end later |
| Python 3.9–3.14 | `Invalid control character at: line 1 column 17 (char 16)` | `json.loads(text, strict=False)` |
| Go 1.25–1.26 | `invalid character '\n' in string literal` | None |
| Go 1.27 | `invalid character '\n' in string` | None |
| Java, Jackson 2.15–2.23 | `Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value` | `JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS` |
| C#, System.Text.Json 10 | `'0x0A' is invalid within a JSON string. The string should be correctly escaped.` | None |
| C#, Newtonsoft.Json 13 | No error | Accepts raw control characters by default |
| PHP 8.3 | `Control character error, possibly incorrectly encoded` | None; error code 3 |
| Rust, serde_json 1.0 | `control character (\u0000-\u001F) found while parsing a string at line 2 column 0` | None |
| jq 1.7.1 | `Invalid string: control characters from U+0000 through U+001F must be escaped at line 2, column 9` | None |
| MySQL 8.4: JSON column | `Invalid JSON text: "Invalid encoding in string." at position 16` | None |
| JSON Statham [Validator](https://jsonstatham.dev/validator/) | Control character in string, line 1, column 17 | None; code `control_character` |

Positions disagree because parsers count differently: V8 and Python count characters from 0, the line break itself starts “line 2” for serde_json and jq, and C# counts bytes in the line. They all point at the same character.

## How to fix control characters in JSON strings

The lasting fix is on the side that writes the JSON: let a serializer escape the string. To rescue a document that is already broken, Python’s `strict=False` reads it and `json.dumps` writes it back valid. All snippets were run as shown.

### JavaScript: a template literal versus JSON.stringify

```js
const note = 'line one\nline two\tend';

const broken = `{"note":"${note}"}`;
const valid = JSON.stringify({ note });

console.log(valid); // {"note":"line one\nline two\tend"}
```

### Python: repair a broken document

```python
import json

data = json.loads(broken_text, strict=False)
fixed = json.dumps(data, ensure_ascii=False)
print(fixed)  # {"note": "line one\nline two\tend"}
```

### Go

```go
import "encoding/json"

func noteJSON(note string) ([]byte, error) {
	return json.Marshal(map[string]string{"note": note})
}
```

### Java (Jackson)

```java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;

static String noteJson(ObjectMapper mapper, String note) throws JsonProcessingException {
    return mapper.writeValueAsString(Map.of("note", note));
}
```

### C# (System.Text.Json)

```csharp
using System.Text.Json;

var json = JsonSerializer.Serialize(new { note = "line one\nline two\tend" });
Console.WriteLine(json); // {"note":"line one\nline two\tend"}
```

### PHP

```php
$json = json_encode(['note' => "line one\nline two\tend"], JSON_THROW_ON_ERROR);
echo $json; // {"note":"line one\nline two\tend"}
```

## How to keep raw control characters out

- **Never build JSON by concatenation.** Templates, `printf`, shell `echo` and database string functions don’t escape anything. `JSON.stringify`, `json.dumps`, `json.Marshal`, Jackson, `JsonSerializer` and `json_encode` escape every control character.
- **Strip colour codes from logs** before you embed them: the escape character U+001B that starts them is a control character too.
- **Treat lenient modes as a repair tool.** Python’s `strict=False` and Jackson’s feature accept the input; write the result back with a serializer so the next reader doesn’t need the same switch.
- **Keep each JSON Lines record on one line.** A raw line break in a string splits the record in two; see [JSON Lines](https://jsonstatham.dev/guides/json-lines/).

## Find the control character in the validator

[Try it: open the control-character sample in the Validator](https://jsonstatham.dev/validator/?sample=control_character). The error card names the character, for example “line break (U+000A)” or “tab (U+0009)”, and Show me (F8) puts the cursor on it. A backslash followed by a raw line break gets the same code: the problem is the raw character, not the escape.

- [Invalid escape](https://jsonstatham.dev/errors/invalid-escape/): a backslash followed by a letter JSON doesn’t know.
- [Unclosed string](https://jsonstatham.dev/errors/unclosed-string/): a quote that is never closed at all.
- [Pretty print JSON](https://jsonstatham.dev/guides/pretty-print-json/): formatting adds line breaks between tokens, never inside strings.
- [All JSON errors](https://jsonstatham.dev/errors/)

## Control characters in JSON: FAQ

### Which characters must be escaped in a JSON string?

The quotation mark, the backslash and every character from U+0000 to U+001F. Short forms exist for `\b`, `\f`, `\n`, `\r` and `\t`; the rest are written as `\u0000` to `\u001f`.

### Can a JSON string span several lines?

Not as typed. A line break inside a string is written as `\n`. The document itself can be spread over many lines, but each string stays on one.

### Is a tab allowed in JSON?

Between tokens, yes: it is ordinary whitespace. Inside a string only escaped, as `\t`.

### Why does Safari say “Unterminated string”?

JavaScriptCore stops at the raw control character and reports the string as unfinished. The closing quote is there; the character where it stopped is the real problem.
