Bad escaped character in JSON (Python: Invalid \escape)

Inside a JSON string a backslash always starts an escape, and only nine are allowed: \", \\, \/, \b, \f, \n, \r, \t and \uXXXX with exactly four hex digits. Any other letter after a backslash, such as the U in C:\Users, is rejected. To store a literal backslash, write two.

Seen as:

  • SyntaxError: Bad escaped character in JSON at position 19 (line 2 column 18)
  • SyntaxError: JSON.parse: bad escaped character at line 2 column 18 of the JSON data
  • json.decoder.JSONDecodeError: Invalid \escape: line 2 column 17 (char 18)
  • SyntaxError: Bad Unicode escape in JSON at position 11 (line 1 column 12)
  • json.decoder.JSONDecodeError: Invalid \uXXXX escape: line 1 column 9 (char 8)

Input

Settings

History

Load from URL

Common causes

1. Windows file paths

Each backslash in a path must be doubled. Forward slashes also work in almost every Windows API and avoid the problem entirely. Watch out: C:\new and C:\temp do not fail, they silently turn into a newline and a tab.

Before
{"logFile": "C:\Users\ada\app.log"}
After
{"logFile": "C:\\Users\\ada\\app.log"}

2. Regular expressions

Patterns such as \d, \w and \s need their backslash escaped in JSON, so \d becomes \\d. The parsed string then contains the single backslash the regex engine expects.

Before
{"datePattern": "\d{4}-\d{2}-\d{2}"}
After
{"datePattern": "\\d{4}-\\d{2}-\\d{2}"}

3. Escapes borrowed from other languages

\' (JavaScript), \x41 (JavaScript, Python, C) and \a or \v © are not JSON escapes. Drop the backslash before an apostrophe and write other characters as \u escapes.

Before
{"note": "It\'s \x41 grade"}
After
{"note": "It's \u0041 grade"}

4. A short or malformed \u escape

\u must be followed by exactly four hexadecimal digits. Characters outside the Basic Multilingual Plane, such as emoji, are written as two escapes (a surrogate pair) or simply pasted as UTF-8.

Before
{"accent": "caf\u00e", "smile": "\u{1F600}"}
After
{"accent": "caf\u00e9", "smile": "\ud83d\ude00"}

Frequently asked questions

Why did C:\temp\new parse without an error but come out wrong?

\t and \n are valid JSON escapes, so the parser turned them into a tab and a newline. Only escapes that are not on the allowed list cause an error, which is why some paths fail and others are silently corrupted.

Do I need to escape forward slashes?

No. / is allowed but optional; it exists so JSON can be embedded in an HTML script tag without forming “</”. Plain / is fine everywhere else.

How do I avoid escaping problems altogether?

Never write JSON strings by hand in code. Build a data structure and serialize it with JSON.stringify, json.dumps or your language’s equivalent; they always produce valid escapes.

Related