FoundationAgents/MetaGPT · error · JSONDecodeError

Invalid \\escape: {0!r}

Error message

Invalid \\escape: {0!r}

What it means

Raised inside py_scanstring: after a backslash, the following character is not 'u' and is not in the BACKSLASH escape lookup table ({\" \\ / b f n r t}), so it is not a valid JSON escape sequence.

Source

Thrown at metagpt/utils/custom_decoder.py:255

        elif terminator != "\\":
            if strict:
                # msg = "Invalid control character %r at" % (terminator,)
                msg = "Invalid control character {0!r} at".format(terminator)
                raise JSONDecodeError(msg, s, end)
            else:
                _append(terminator)
                continue
        try:
            esc = s[end]
        except IndexError:
            raise JSONDecodeError("Unterminated string starting at", s, begin) from None
        # If not a unicode escape sequence, must be in the lookup table
        if esc != "u":
            try:
                char = _b[esc]
            except KeyError:
                msg = "Invalid \\escape: {0!r}".format(esc)
                raise JSONDecodeError(msg, s, end)
            end += 1
        else:
            uni = _decode_uXXXX(s, end)
            end += 5
            if 0xD800 <= uni <= 0xDBFF and s[end : end + 2] == "\\u":
                uni2 = _decode_uXXXX(s, end + 1)
                if 0xDC00 <= uni2 <= 0xDFFF:
                    uni = 0x10000 + (((uni - 0xD800) << 10) | (uni2 - 0xDC00))
                    end += 6
            char = chr(uni)
        _append(char)
    return "".join(chunks), end


scanstring = py_scanstring


class CustomDecoder(json.JSONDecoder):

View on GitHub (pinned to 11cdf466d0)

Solutions

  1. Double every literal backslash in the JSON string (\\d -> \\\\d).
  2. Build the JSON with json.dumps so escaping is handled automatically.
  3. Pre-normalize the text with a regex that doubles lone backslashes not part of valid escapes.
  4. If the source is an LLM, prompt it to emit valid JSON escapes or re-run the generation.

Example fix

// before
'{"pattern": "\\d{3}"}'  # Invalid \\escape: 'd'

// after
'{"pattern": "\\\\d{3}"}'  # or in Python: json.dumps({"pattern": r"\d{3}"})
Defensive patterns

Strategy: validation

Validate before calling

import re
VALID = set('"\\/bfnrtu')
def escapes_valid(s: str) -> bool:
    return all(m.group(1) in VALID for m in re.finditer(r'\\(.)', s))

Try / catch

try:
    obj = decoder.decode(s)
except json.JSONDecodeError as e:
    if e.msg.startswith('Invalid \\escape'):
        obj = decoder.decode(re.sub(r'\\(?!["\\/bfnrtu])', r'\\\\', s))

Prevention

When it happens

Trigger: Decoding strings containing invalid escapes such as \\x, \\a, \\ ', or \\d — e.g. '{"re": "\\d+"}' where the intent was a regex but the backslash is not doubled, or Python-style escapes (\\x41) inside JSON.

Common situations: Embedding regular expressions, Windows paths, or LaTeX/markdown text into JSON without escaping backslashes; LLMs emitting single backslashes in regex values; converting Python string literals to JSON with str() instead of json.dumps.

Related errors


AI-assisted analysis of FoundationAgents/MetaGPT@11cdf466d0 (2026-08-14). Data as JSON: /api/errors/0da53ef4cb8de563. Report an issue: GitHub.