Skip to content

Add details for JSON serialization errors #122163

Closed
@serhiy-storchaka

Description

@serhiy-storchaka

Feature or enhancement

When an JSON unserializable object occurs deeply in the large structure, it is difficult to find the culprit, because the error message by default only contains the type of the unserializable object. This is pretty common error, for example you can forget to convert the datetime object to timestamp or string.

The proposed PR adds notes to the raised exception which allow to identify the source of the error. For example:

>>> import json
>>> json.dumps([{'a': 1, 'b': 2}, {'a': 3, 'b': ...}])
Traceback (most recent call last):
  File "<python-input-16>", line 1, in <module>
    json.dumps([{'a': 1, 'b': 2}, {'a': 3, 'b': ...}])
    ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/serhiy/py/cpython/Lib/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
           ~~~~~~~~~~~~~~~~~~~~~~~^^^^^
  File "/home/serhiy/py/cpython/Lib/json/encoder.py", line 200, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/home/serhiy/py/cpython/Lib/json/encoder.py", line 261, in iterencode
    return _iterencode(o, 0)
  File "/home/serhiy/py/cpython/Lib/json/encoder.py", line 180, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
                    f'is not JSON serializable')
TypeError: Object of type ellipsis is not JSON serializable
when serializing dict item 'b'
when serializing list item 1

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions