django error: ValueError: Circular reference detected

created at 07-17-2021 views: 128

detailed error message

File "C:\Python27\MyDjango\jianzhi_002\jianzhi_app\", line 418, in wx_get_job_detail
    return HttpResponse(json.dumps({'message': message, 'data': detail_data}))
File "C:\Python27\lib\json\", line 244, in dumps
    return _default_encoder.encode(obj)
File "C:\Python27\lib\json\", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
File "C:\Python27\lib\json\", line 270, in iterencode
    return _iterencode(o, 0)
ValueError: Circular reference detected

meaning: there is a circular reference.

Code reproduction:

import json

a = b = c = {}
# Save b, c to a
a['b'] = b
a['c'] = c

error prompt

ValueError                                Traceback (most recent call last)
<ipython-input-5-2f50cf32d976> in <module>()
----> 1 json.dumps(a)

/usr/lib/python2.7/json/__init__.pyc in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, encoding, default, sort_keys, **kw)
    241         cls is None and indent is None and separators is None and
    242         encoding == 'utf-8' and default is None and not sort_keys and not kw):
--> 243         return _default_encoder.encode(obj)
    244     if cls is None:
    245         cls = JSONEncoder

/usr/lib/python2.7/json/encoder.pyc in encode(self, o)
    205         # exceptions aren't as detailed.  The list call should be roughly
    206         # equivalent to the PySequence_Fast that ''.join() would do.
--> 207         chunks = self.iterencode(o, _one_shot=True)
    208         if not isinstance(chunks, (list, tuple)):
    209             chunks = list(chunks)

/usr/lib/python2.7/json/encoder.pyc in iterencode(self, o, _one_shot)
    268                 self.key_separator, self.item_separator, self.sort_keys,
    269                 self.skipkeys, _one_shot)
--> 270         return _iterencode(o, 0)
    272 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,

ValueError: Circular reference detected

The reason is that a b c actually points to a reference to the same object.


import json

a, b, c = {}, {}, {}
# Save b, c to a
a['b'] = b
a['c'] = c


Generally, ValueError: Circular reference detected errors are encountered because the same variable is circularly referenced. Check which variable in the code is referenced circularly and just change the variable name.

created at:07-17-2021
edited at: 07-17-2021: