Skip to content

API reference

Everything is available from import expatjson.

Converting

parse

parse(xml, *, max_size=20 * 1024 * 1024, max_depth=200, backend="auto") -> dict

Convert XML to a dict.

Argument Type Description
xml str / bytes / bytearray / memoryview the whole document
max_size int input size limit in bytes
max_depth int element nesting limit (1 or more)
backend str "auto", "native" or "python"

Returns a dict keyed by the root element name. Values are dict, list, str or None.

Raises a subclass of ExpatJsonError; ValueError for invalid argument values.

to_json

to_json(xml, *, indent=None, ensure_ascii=False, **options) -> str

Convert to a JSON string, without extra spaces unless indent is given. options are passed to parse.

parse_file

parse_file(path, **options) -> dict

Read and convert a file (never more than max_size bytes). Raises FileReadError.

parse_gzip

parse_gzip(data, **options) -> dict

Decompress gzip and convert. max_size also limits the decompressed size. Raises CompressionError.

parse_gzip_base64

parse_gzip_base64(data, **options) -> dict

Decode Base64, then call parse_gzip.

Helpers

as_list

as_list(value) -> list

None becomes [], a list is returned as is, anything else becomes a one-item list.

get_path

get_path(document, *keys, default=None)

Follow dict keys and list indexes; return default if something is missing.

backend

backend() -> str

The parser used by backend="auto": "native" or "python".

set_language

set_language(language) -> None

Language of error messages, "ja" (default) or "en", for the whole process.

Constants

Name Value
DEFAULT_MAX_SIZE 20971520 (20 MiB)
DEFAULT_MAX_DEPTH 200
__version__ library version

Exceptions

See Error handling.

Environment variables

Environment variable Effect
EXPATJSON_BACKEND=python do not load the C++ extension
EXPATJSON_LANG=en English error messages
EXPATJSON_PURE=1 do not build the C++ extension
EXPATJSON_REQUIRE_NATIVE=1 fail if the C++ extension cannot be built