ValueError: Circular Reference in JSON

ValueError: Circular reference detected

Quick Answer

Your data has a circular reference. JSON cannot represent cycles. Remove the cycle or use a custom serializer.

Why This Happens

JSON is tree-structured and cannot represent circular references. This often occurs with ORM objects that have bidirectional relationships.

The Problem

import json
a = {'name': 'A'}
b = {'name': 'B', 'ref': a}
a['ref'] = b
json.dumps(a)

The Fix

import json
a = {'name': 'A'}
b = {'name': 'B', 'ref': a}
# Select specific fields instead:
json.dumps({'name': a['name']})

Step-by-Step Fix

  1. 1

    Remove circular references

    Break cycles before serialization.

  2. 2

    Select specific fields

    Build a dict with only needed fields.

  3. 3

    Use a custom encoder

    Track seen objects and handle cycles.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free