On this page
  1. json.JSONEncoder
  2. Import
  3. Signature & Overview
  4. Methods & Attributes
  5. Usage
  6. Gotchas
  7. REPL Inspect

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

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

REPL Inspect

from json import JSONEncoder
help(JSONEncoder)

Linked from

Related notes