Zie619/n8n-workflows · error · HTTPException

Invalid JSON in workflow file: {str(e)}

Error message

Invalid JSON in workflow file: {str(e)}

What it means

A 400 from GET /api/workflows/{filename}/diagram raised by the dedicated except json.JSONDecodeError branch: the workflow file was found and opened, but json.load() failed to parse it. The parser's message (line/column, 'Expecting value', 'Extra data') is embedded in the detail, and the server prints 'Error parsing JSON in {filename}'. This branch fires before the generic 500 handler, distinguishing malformed content from other failures.

Source

Thrown at api_server.py:492

                status_code=404,
                detail=f"Workflow file '{filename}' not found on filesystem",
            )

        with open(matching_file, "r", encoding="utf-8") as f:
            data = json.load(f)

        nodes = data.get("nodes", [])
        connections = data.get("connections", {})

        # Generate Mermaid diagram
        diagram = generate_mermaid_diagram(nodes, connections)

        return {"diagram": diagram}
    except HTTPException:
        raise
    except json.JSONDecodeError as e:
        print(f"Error parsing JSON in {filename}: {str(e)}")
        raise HTTPException(
            status_code=400, detail=f"Invalid JSON in workflow file: {str(e)}"
        )
    except Exception as e:
        print(f"Error generating diagram for {filename}: {str(e)}")
        raise HTTPException(
            status_code=500, detail=f"Error generating diagram: {str(e)}"
        )


def generate_mermaid_diagram(nodes: List[Dict], connections: Dict) -> str:
    """Generate Mermaid.js flowchart code from workflow nodes and connections."""
    if not nodes:
        return "graph TD\n  EmptyWorkflow[No nodes found in workflow]"

    # Create mapping for node names to ensure valid mermaid IDs
    mermaid_ids = {}
    for i, node in enumerate(nodes):
        node_id = f"node{i}"

View on GitHub (pinned to 94007c1445)

Solutions

  1. Validate the file locally: python -m json.tool workflows/<subdir>/<file>.json — it reports the same error with position.
  2. Fix the JSON at the reported line/column (the detail string includes it) or restore the file from git.
  3. Re-save files as UTF-8 without BOM and ensure writes are atomic (write temp, rename).
  4. After repair, the diagram endpoint will parse it without reindexing (diagrams read the file directly).

Example fix

# before (trailing comma breaks parsing)
{ "name": "flow", "nodes": [], }

# after
{ "name": "flow", "nodes": [] }
Defensive patterns

Strategy: validation

Validate before calling

import json, pathlib

def parses_cleanly(path):
    try:
        json.loads(pathlib.Path(path).read_text(encoding='utf-8-sig'))
        return True
    except json.JSONDecodeError:
        return False

Try / catch

try:
    d = client.get(f'/api/workflows/{name}/diagram').json()['diagram']
except HTTPError as e:
    detail = e.response.json().get('detail', '')
    if e.response.status_code == 400 and 'Invalid JSON' in detail:
        quarantine(name, detail)  # file content bug — fix the JSON

Prevention

When it happens

Trigger: Downloading a diagram for a file truncated mid-write, containing a UTF-8 BOM, holding concatenated JSON objects ('Extra data'), or actually being HTML/error text saved with a .json extension.

Common situations: Hand-edited workflow files with trailing commas or unescaped quotes; files synced incompletely; Windows editors saving with BOM; empty files from a failed export.

Understand the failure class

Related errors


AI-assisted analysis of Zie619/n8n-workflows@94007c1445 (2026-08-15). Data as JSON: /api/errors/17001710b601bee3. Report an issue: GitHub.