On this page
json.JSONEncoder
Prev: json.JSONDecoder | Up: json | Next: json.load
Rel: json.dump, json.dumps, json.JSONDecodeError, json.JSONDecoder
Ref: docs.python.org — json.JSONEncoder
Tags: #public #python3 #stdlib #json
Import
import json
from json import JSONEncoder
Signature & Overview
json.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.
Methods & Attributes
JSONEncoder.default(self, o)— Implement this method in a subclass such that it returns a serializable object foro, or calls the base implementation (to raise aTypeError).JSONEncoder.encode(self, o)— Return a JSON string representation of a Python data structure.JSONEncoder.iterencode(self, o, _one_shot=False)— Encode the given object and yield each string representation as available.
Usage
import json
from pathlib import Path
class PathEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, Path):
return str(o)
return super().default(o)
out = json.dumps({"root": Path("/tmp/demo")}, cls=PathEncoder)
assert out == '{"root": "/tmp/demo"}'
Gotchas
- Always call
super().default(o)as fallback: That preserves the standardTypeErrorfor genuinely unsupported types. - Simple cases don't need a subclass: Passing
default=my_functojson.dumps()is usually shorter than defining aJSONEncodersubclass.
REPL Inspect
from json import JSONEncoder
help(JSONEncoder)
Linked from
Related notes
- tuts/python3/stdlib_module/json/dump Linked here; links to this page; shared tags: #json, #stdlib
- tuts/python3/stdlib_module/json/dumps Linked here; links to this page; shared tags: #json, #stdlib
- tuts/python3/stdlib_module/json/JSONDecodeError Linked here; links to this page; shared tags: #json, #stdlib
- tuts/python3/stdlib_module/json/JSONDecoder Linked here; links to this page; shared tags: #json, #stdlib
- tuts/python3/stdlib_module/json/load Linked here; links to this page; shared tags: #json, #stdlib
- tuts/python3/stdlib_module/json Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/json/loads shared tags: #json, #stdlib
- tuts/c/stdlib shared tags: #stdlib
- tuts/c/stdlib/assert shared tags: #stdlib
- tuts/c/stdlib/assert/assert shared tags: #stdlib