django error: ValueError: Circular reference detected

created at 07-17-2021 views: 1

detailed error message

File "C:\Python27\MyDjango\jianzhi_002\jianzhi_app\views.py", line 418, in wx_get_job_detail
    return HttpResponse(json.dumps({'message': message, 'data': detail_data}))
File "C:\Python27\lib\json\__init__.py", line 244, in dumps
    return _default_encoder.encode(obj)
File "C:\Python27\lib\json\encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
File "C:\Python27\lib\json\encoder.py", 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
json.dumps(a)

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)
    271 
    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.

Solution

import json

a, b, c = {}, {}, {}
# Save b, c to a
a['b'] = b
a['c'] = c
json.dumps(a)

summary

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.

Please log in to leave a comment.