PyDocs

Nav

Internet Data Handling

JSONEncoder

json

class (source)
  • JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)
Extensible JSON <https://json.org> encoder for Python data structures.

Supports the following objects and types by default:

+-------------------+---------------+
| Python            | JSON          |
+===================+===============+
| dict, frozendict  | object        |
+-------------------+---------------+
| list, tuple       | array         |
+-------------------+---------------+
| str               | string        |
+-------------------+---------------+
| int, float        | number        |
+-------------------+---------------+
| True              | true          |
+-------------------+---------------+
| False             | false         |
+-------------------+---------------+
| None              | null          |
+-------------------+---------------+

To extend this to recognize other objects, subclass and implement a
``.default()`` method with another method that returns a serializable
object for ``o`` if possible, otherwise it should call the superclass
implementation (to raise ``TypeError``).
Changed in 3.2, 3.4, 3.6, 3.15
  • 3.2: Allow strings for indent in addition to integers.
  • 3.4: Added support for int- and float-derived Enum classes.
  • 3.4: Use (',', ': ') as default if indent is not None.
  • 3.6: All parameters are now keyword-only.
  • 3.15: Added support for frozendict.
Members of JSONEncoder

d

default
Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``).

e

encode
Return a JSON string representation of a Python data structure.

i

iterencode
Encode the given object and yield each string representation as available.
1 Example
>>> import json
>>> class ComplexEncoder(json.JSONEncoder):
...     def default(self, obj):
...         if isinstance(obj, complex):
...             return [obj.real, obj.imag]
...         # Let the base class default method raise the TypeError
...         return super().default(obj)
...
>>> json.dumps(2 + 1j, cls=ComplexEncoder)
'[2.0, 1.0]'
>>> ComplexEncoder().encode(2 + 1j)
'[2.0, 1.0]'
>>> list(ComplexEncoder().iterencode(2 + 1j))
['[2.0', ', 1.0', ']']
from the Python docs
See Also
No see-alsos for json/JSONEncoder
0 Notes
No notes for JSONEncoder