JSON Invalid Escape Sequence Error: Fix It Fast (2026)
Getting a 'JSON invalid escape sequence' error? This guide covers every cause — Windows paths, regex, LLM output, LaTeX — and shows exact fixes in JavaScript and Python.
Have broken JSON right now? Fix it free in under 1 second — no signup.
Fix My JSON →A JSON invalid escape sequence error means a backslash (\) appears inside a string value followed by a character that JSON doesn't recognize as a valid escape. JSON has a short, fixed list of valid escape sequences — anything outside that list causes a parse failure.
This is a very common error when dealing with Windows file paths, regular expressions, LLM-generated content with LaTeX formulas, or any string built by concatenation rather than proper serialization.
What the Error Looks Like
| Runtime | Error Message |
|---|---|
| Python | json.decoder.JSONDecodeError: Invalid \escape: line X column Y |
| Node.js (≤v18) | SyntaxError: Bad escaped character in JSON at position N |
| Node.js (v20+) | SyntaxError: Invalid escape sequence in JSON |
| Java (Gson) | MalformedJsonException: Invalid escape sequence |
| Go | invalid character 'X' in string escape code |
| PHP | json_last_error() === JSON_ERROR_SYNTAX |
Example that triggers the error:
{ "path": "C:\Users\Documents\report.pdf" }
The parser sees \U (not a valid escape), \D (not valid), and stops immediately.
Valid JSON Escape Sequences
JSON only allows these escape sequences inside strings:
| Escape | Meaning |
|---|---|
\" | Double quote |
\\ | Backslash |
\/ | Forward slash (optional) |
\n | Newline |
\r | Carriage return |
\t | Tab |
\b | Backspace |
\f | Form feed |
\uXXXX | Unicode code point (4 hex digits) |
Everything else — \p, \d, \U, \x, \', \(, \), \s, \w — is invalid in JSON and will cause a parse error.
Note: \xNN hex escapes are valid in JavaScript strings but not in JSON. Use \uXXXX instead.
Common Causes of Invalid Escape Sequences
Windows File Paths (Most Common)
Windows uses backslashes in file paths, and developers often embed paths directly into JSON:
{ "config": "C:\Program Files\MyApp\settings.ini" }
This has three invalid escapes: \P, \M, \s. Fix by doubling all backslashes:
{ "config": "C:\\Program Files\\MyApp\\settings.ini" }
Or use forward slashes — Windows accepts them in most API contexts:
{ "config": "C:/Program Files/MyApp/settings.ini" }
Regex Patterns
Regular expressions frequently contain backslashes. A regex like \d+\.\d+ breaks when embedded directly into JSON:
{ "pattern": "\d+\.\d+" }
\d is not a valid JSON escape. Fix by escaping the backslash:
{ "pattern": "\\d+\\.\\d+" }
In Python, the raw string approach:
import json
import re
# Don't concatenate regex directly into JSON strings
pattern = r"\d+\.\d+" # Python raw string: backslashes are literal
json_str = json.dumps({"pattern": pattern}) # Handles escaping for you
print(json_str) # {"pattern": "\\d+\\.\\d+"}
# To use the regex back after parsing:
parsed = json.loads(json_str)
compiled = re.compile(parsed["pattern"])
print(compiled.match("3.14")) # Match!
LaTeX Formulas in LLM Output
AI pipelines that process or generate mathematical content often break JSON. When an LLM embeds LaTeX in a JSON response, it may output:
{ "formula": "The result is \(\alpha + \beta\) where \(\gamma = 42\)" }
\(, \), \a, \b (except \b = backspace) are invalid or ambiguous. This is an active issue in 2026 — reported in graphiti #1204 (LLM entity extraction fails on LaTeX), and seen broadly in pipelines that process academic or scientific text.
Fix: instruct the LLM to escape backslashes, or post-process the output:
import re
from jsonrepair import repair_json
def fix_latex_in_json(raw_json: str) -> str:
"""
Fix invalid backslash escapes from LLM-generated JSON with LaTeX.
Doubles any single backslash not already part of a valid JSON escape.
"""
valid_escapes = set('"\\\/nrtbf')
def fix_string(m):
s = m.group(0)
result = []
i = 0
while i < len(s):
if s[i] == '\\' and i + 1 < len(s):
next_char = s[i + 1]
if next_char in valid_escapes or (next_char == 'u' and i + 5 < len(s)):
result.append(s[i:i+2])
i += 2
else:
result.append('\\\\') # Escape the lone backslash
i += 1
else:
result.append(s[i])
i += 1
return ''.join(result)
# Apply to string values in JSON
return re.sub(r'"(?:[^"\\]|\\.)*"', fix_string, raw_json)
For a simpler approach, pass the raw output through jsonrepair:
from jsonrepair import repair_json
repaired = repair_json(raw_llm_output)
The jsonrepair library handles most invalid escape sequences automatically.
Hex Escape Codes (\x)
JavaScript allows \x41 (hex for "A") in string literals, but JSON does not. Only \uXXXX (4 hex digits) is valid in JSON:
{ "char": "\x41" } // Invalid JSON — \x is not a valid JSON escape
{ "char": "\u0041" } // Valid — Unicode for "A"
This typically appears when JSON is generated by JavaScript code that uses \x escapes:
// Problem:
const json = '{"char": "\x41"}'; // JavaScript parses \x41 = "A" before JSON.parse sees it
// So actually json = '{"char": "A"}' — this works because JS resolves \x41 first
// Real problem: when the \x comes from a data source, not a JS literal
const raw = `{"regex": "${someVariable}"}`; // If someVariable contains \x, breaks JSON.parse
Fix: always use JSON.stringify() to serialize values, which converts any character to valid JSON escapes.
Single-Quote Escapes (\')
\' is not a valid JSON escape. It comes up when developers port JavaScript template literals or PHP single-quoted strings to JSON:
{ "message": "It\'s a valid message" } // Invalid — \' not in JSON spec
{ "message": "It's a valid message" } // Valid — no escape needed for ' in JSON
Single quotes in JSON strings don't need escaping. Only " needs \".
Unicode Code Points Above \uFFFF
Emoji and extended Unicode characters need surrogate pairs in JSON if outside the Basic Multilingual Plane:
import json
# Python handles this automatically:
data = {"emoji": "😊"}
print(json.dumps(data)) # {"emoji": "\ud83d\ude0a"} or the raw emoji
print(json.dumps(data, ensure_ascii=True)) # {"emoji": "\ud83d\ude0a"}
print(json.dumps(data, ensure_ascii=False)) # {"emoji": "😊"}
# Both are valid JSON. Problems arise when you manually construct \u codes wrong:
broken = '{"emoji": "\\u1F60A"}' # Wrong: 5 hex digits
valid = '{"emoji": "\\uD83D\\uDE0A"}' # Right: surrogate pair
How to Fix Invalid Escape Sequences
Fix 1: Auto-Repair Online
Paste the broken JSON into AI JSONMedic. The repair engine identifies and fixes invalid escape sequences — most commonly doubling lone backslashes and converting \x to \u equivalents. Results in seconds.
Fix 2: Python — Use json.dumps() for Serialization
The root fix for most cases: never build JSON by string concatenation.
import json
# Problem: manual string building
windows_path = r"C:\Users\Alice\Documents"
broken_json = '{"path": "' + windows_path + '"}' # Backslashes not escaped
# broken_json = '{"path": "C:\Users\Alice\Documents"}' # INVALID
# Fix: let json.dumps handle the escaping
correct_json = json.dumps({"path": windows_path})
# correct_json = '{"path": "C:\\\\Users\\\\Alice\\\\Documents"}' # Valid
print(json.loads(correct_json)) # {'path': 'C:\\Users\\Alice\\Documents'}
Fix 3: Python — Repair with jsonrepair
import json
from jsonrepair import repair_json # pip install jsonrepair
def safe_parse(raw: str):
try:
return json.loads(raw)
except json.JSONDecodeError:
return json.loads(repair_json(raw))
# Windows path with unescaped backslashes
broken = r'{"path": "C:\Users\Alice\report.pdf"}'
result = safe_parse(broken)
print(result) # {'path': 'C:\\Users\\Alice\\report.pdf'}
# Regex pattern with unescaped backslashes
broken2 = '{"pattern": "\\d+\\.\\d+"}' # \d not valid in JSON
result2 = safe_parse(broken2)
print(result2)
Fix 4: JavaScript — Use JSON.stringify() for Serialization
// Problem: building JSON by template literal
const windowsPath = "C:\\Users\\Alice\\Documents"; // JS string, one backslash each
const brokenJson = `{"path": "${windowsPath}"}`;
// brokenJson = '{"path": "C:\Users\Alice\Documents"}' — INVALID
// Fix: JSON.stringify handles all escaping
const correctJson = JSON.stringify({ path: windowsPath });
// correctJson = '{"path": "C:\\\\Users\\\\Alice\\\\Documents"}' — Valid
// For regex patterns:
const pattern = /\d+\.\d+/;
const patternJson = JSON.stringify({ pattern: pattern.source });
// patternJson = '{"pattern": "\\d+\\.\\d+"}' — Valid
Fix 5: JavaScript — Repair with json-repair
import { jsonrepair } from 'json-repair'; // npm install json-repair
function safeParse(raw) {
try {
return JSON.parse(raw);
} catch {
return JSON.parse(jsonrepair(raw));
}
}
// LLM output with LaTeX backslashes
const broken = '{"formula": "The result is \\(\\alpha + \\beta\\)"}';
// If the LLM didn't escape \( and \) properly:
const broken2 = String.raw`{"formula": "The result is \(\alpha + \beta\)"}`;
const result = safeParse(broken2);
console.log(result); // { formula: 'The result is (\\alpha + \\beta)' }
Fix 6: Bulk Fix — Replace Single Backslashes
For JSON files where the only issue is unescaped single backslashes (like exported Windows paths), a targeted replace can work:
import re
import json
def fix_lone_backslashes(raw_json: str) -> str:
"""
Replace lone backslashes (not already doubled) with double backslashes.
Only applies outside of already-valid escape sequences.
"""
# This is a simplified approach — for complex cases use jsonrepair
valid_after_backslash = set('"\\\/nrtbfu')
result = []
i = 0
while i < len(raw_json):
if raw_json[i] == '\\':
if i + 1 < len(raw_json) and raw_json[i+1] in valid_after_backslash:
result.append(raw_json[i]) # Keep valid escape
i += 1
else:
result.append('\\\\') # Double the lone backslash
else:
result.append(raw_json[i])
i += 1
return ''.join(result)
broken = '{"path": "C:\\Users\\Alice", "pattern": "\\d+"}'
fixed = fix_lone_backslashes(broken)
print(json.loads(fixed))
# {'path': 'C:\\Users\\Alice', 'pattern': '\\d+'}
Preventing Invalid Escape Sequences
Always Use Language Serialization
The single most effective prevention: never build JSON strings manually.
# Wrong — invites escape errors:
json_str = '{"key": "' + some_value + '"}'
# Right — handles all escaping:
json_str = json.dumps({"key": some_value})
// Wrong:
const jsonStr = `{"key": "${someValue}"}`;
// Right:
const jsonStr = JSON.stringify({ key: someValue });
Validate Before Storing
Before writing JSON to a database, file, or API response, validate that it parses:
import json
def safe_json_write(data: dict, filepath: str):
json_str = json.dumps(data, ensure_ascii=False)
# Verify it round-trips correctly
assert json.loads(json_str) == data, "JSON round-trip failed"
with open(filepath, "w", encoding="utf-8") as f:
f.write(json_str)
Sanitize LLM Output Before Parsing
For LLM pipelines, add a repair step:
import json
from jsonrepair import repair_json
def parse_llm_output(raw: str) -> dict:
"""Parse LLM JSON with automatic escape repair."""
try:
return json.loads(raw)
except json.JSONDecodeError:
repaired = repair_json(raw)
return json.loads(repaired)
See the LLM JSON Repair Guide for a full production-ready implementation with logging and fallback strategies.
FAQ
Q: I'm getting "Invalid \\escape" in Python. What does the double backslash mean?Python's error message shows \\escape because it's displaying the backslash character in its escaped form. The actual JSON contained a single \ followed by an invalid character. The fix is to escape that backslash as \\ in your JSON source.
Yes — run it through repair_json (Python) or jsonrepair (JavaScript) before parsing. Both libraries automatically fix most invalid escape sequences, including common Windows path and regex patterns.
\uXXXX escapes cause this error?
Only if the hex digits are wrong. \u must be followed by exactly 4 hexadecimal digits (0-9, a-f, A-F). \u123 (3 digits), \uGHIJ (non-hex), or \u1F60A (5 digits) are all invalid and will cause a parse error.
Invalid escape: \X where X is not a valid JSON escape character — the parser knows it's a string but can't understand the escape sequence. Unterminated string: the string " was opened but never closed — the parser ran out of document before finding the matching close quote. See JSON Unterminated String Error Fix for the unterminated string guide.
JSON5 allows \x hex escapes and some additional sequences from JavaScript. JSONC (JSON with Comments) does not add new escape sequences — it only adds comment support. For standard JSON parsers, only the 9 sequences in the table above are valid.
Use json.dumps():
import json
path = r"C:\Users\Alice\Documents" # Python raw string
result = json.dumps({"path": path})
# {"path": "C:\\Users\\Alice\\Documents"}
The json.dumps() function correctly doubles the backslashes automatically.
Related Resources
- JSON Unterminated String Error Fix — for unclosed string value errors
- JSON Missing Bracket Error Fix — for unclosed
{or[errors - JSON Trailing Comma Error Fix — another common JSON syntax error
- Fix Python JSON Errors — complete guide to Python's json module errors
- LLM JSON Repair Guide — fixing AI-generated JSON failures at scale
- JSON Syntax Errors Explained — every JSON error type in one place
- AI JSONMedic JSON Studio — repair, validate, and format JSON in one workspace
Invalid escape sequences almost always come from the same root cause: JSON built by string concatenation instead of proper serialization. Use json.dumps() / JSON.stringify() for everything. When you receive broken JSON from an external source, run it through AI JSONMedic or the jsonrepair library before parsing.
Still dealing with broken JSON?
Paste it in and get it fixed in under 1 second — free, no signup, no install. Works with ChatGPT, Claude, n8n, and any AI output.
Fix My JSON Free →Related Articles