python parse_error ai_generated true

json.decoder.JSONDecodeError: Expecting value

ID: python/jsondecodeerror

Also available as: JSON · Markdown
90%Fix Rate
88%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

Invalid JSON input. Common with empty API responses, HTML error pages, or BOM-prefixed files.

generic

Workarounds

  1. 92% success Check response status and content-type before parsing
    if resp.status_code == 200 and 'json' in resp.headers.get('content-type', ''): data = resp.json()

    Sources: https://docs.python.org/3/library/json.html

  2. 88% success Log the raw content to identify what's actually being returned
    import logging
    logging.debug('Raw response: %r', resp.text[:500])
    # Check: is it HTML error page? Empty string? BOM prefix?

    Sources: https://docs.python.org/3/library/logging.html

Dead Ends

Common approaches that don't work:

  1. Wrap json.loads in try/except and return empty dict 68% fail

    Silently drops real data errors

  2. Use eval() instead of json.loads() 95% fail

    Massive security vulnerability — never eval untrusted data

Error Chain

Frequently confused with: