affaan-m/ECC · error · ValueError

Failed to parse data: {data}

Error message

Failed to parse data: {data}

What it means

A ValueError raised from process_data() when json.loads(data) throws json.JSONDecodeError. The input string could not be parsed as JSON. The original exception is chained via `raise ... from e` so the underlying decode failure is not lost.

Source

Thrown at skills/python-patterns/SKILL.md:172

# Bad: Bare except
def load_config(path: str) -> Config:
    try:
        with open(path) as f:
            return Config.from_json(f.read())
    except:
        return None  # Silent failure!
```

### Exception Chaining

```python
def process_data(data: str) -> Result:
    try:
        parsed = json.loads(data)
    except json.JSONDecodeError as e:
        # Chain exceptions to preserve the traceback
        raise ValueError(f"Failed to parse data: {data}") from e
```

### Custom Exception Hierarchy

```python
class AppError(Exception):
    """Base exception for all application errors."""
    pass

class ValidationError(AppError):
    """Raised when input validation fails."""
    pass

class NotFoundError(AppError):
    """Raised when a requested resource is not found."""
    pass

# Usage

View on GitHub (pinned to 01e15490f0)

Solutions

  1. Log `repr(data[:200])` before parsing to see exactly what was fed to json.loads.
  2. Confirm the upstream source actually returns JSON (check Content-Type header and status code before parsing).
  3. If data may arrive in chunks, buffer until a complete JSON document is available before parsing.
  4. Guard with a type check: if isinstance(data, (dict, list)): return data to avoid re-parsing already-deserialized input.

Example fix

# before
parsed = json.loads(data)

# after: verify the source is JSON before parsing
if not isinstance(data, str):
    return data  # already deserialized
parsed = json.loads(data)
Defensive patterns

Strategy: validation

Validate before calling

def safe_json_loads(data):
    if isinstance(data, (dict, list)):
        return data
    if not isinstance(data, str):
        raise TypeError(f"expected str, got {type(data).__name__}")
    try:
        return json.loads(data)
    except json.JSONDecodeError as e:
        raise ValueError(f"Failed to parse data: {data[:120]!r}") from e

Type guard

from typing import Any
def is_json_string(s: Any) -> bool:
    if not isinstance(s, str):
        return False
    try:
        json.loads(s)
        return True
    except json.JSONDecodeError:
        return False

Try / catch

try:
    parsed = json.loads(data)
except json.JSONDecodeError as e:
    log.warning("unparseable payload (%d bytes): %s", len(data), e)
    raise ValueError(f"Failed to parse data") from e

Prevention

When it happens

Trigger: Calling process_data(data) with a string that is not valid JSON — empty string, HTML error page returned instead of JSON, truncated payload, or data already deserialized (a dict passed where a string was expected).

Common situations: Reading a response body that turned out to be an HTML 502 page; receiving a streaming chunk rather than a complete message; double-decoding (passing already-parsed dict to json.loads); locale-dependent number formatting in serialized data.

Understand the failure class

Related errors


AI-assisted analysis of affaan-m/ECC@01e15490f0 (2026-08-13). Data as JSON: /api/errors/3e635a90d5f90f1e. Report an issue: GitHub.