Skip to content

expatjson

PyPI Downloads Python OS Arch Wheel CI License: MIT

Convert XML to a Python dict or to JSON. Parsing is done by Expat. No dependencies. Prebuilt wheels include a C++ extension, so you do not need a compiler.

pip install expatjson

Features

  • Uses the C++ extension when available, otherwise a pure Python implementation.
  • Needs only the standard library.
  • Rejects DTDs and entity declarations, and limits input size and nesting depth.
  • Errors carry a line, column and error code, with messages in Japanese (default) or English.
  • Attributes become @name, text becomes #text, repeated elements become lists.

Quick start

import expatjson

doc = expatjson.parse('<book id="1"><title>Coffee</title><tag>a</tag><tag>b</tag></book>')
print(doc)
# {'book': {'@id': '1', 'title': 'Coffee', 'tag': ['a', 'b']}}

print(expatjson.to_json('<a><b>1</b></a>'))
# {"a":{"b":"1"}}

Performance

Measured on Windows 10, Python 3.11 (generated documents, median of 7 runs). Results depend on documents and platform; run python bench/bench.py.

Parser 1.5 KiB 149 KiB 3 MiB
expatjson (native) 0.18 ms 11.2 ms 264 ms
expatjson (Python) 0.30 ms 27.3 ms 480 ms
xmltodict 1.0.4 0.57 ms 53.2 ms 1064 ms

Next