xmltojson
xmltojson is a Python module and command-line tool designed to quickly convert XML text or files into JSON format. It aims to provide a straightforward conversion mechanism for common use cases. The current stable version is 2.0.3, with releases typically focusing on stability and minor feature enhancements.
Warnings
- gotcha Conversion of single-element XML lists to JSON arrays can be inconsistent. XML does not inherently distinguish between a single element and a list of one element. Some converters might output a single JSON object instead of a JSON array containing one object, which can break consuming code expecting an array.
- gotcha XML is fundamentally text-based, so numerical, boolean, or null values in XML often get converted to strings in JSON. This can lead to type mismatches in downstream applications expecting specific JSON data types.
- gotcha XML attributes and namespaces are handled according to the underlying conversion logic (likely `xmltodict`). By default, attributes might be prefixed (e.g., with '@') or even omitted, and namespaces may be stripped or embedded in the key names, which might not be intuitive or desired.
- gotcha Providing malformed or empty XML input can lead to conversion failures, often manifesting as an 'ExecutionFailed' error (if using it in a larger pipeline or CLI context), or parsing exceptions.
Install
-
pip install xmltojson
Imports
- xmltojson
import xmltojson
Quickstart
import xmltojson
xml_string = '<person><name>Alice</name><age>30</age></person>'
json_output = xmltojson.parse(xml_string)
print(json_output)
# Expected output: {"person": {"name": "Alice", "age": "30"}} (exact formatting may vary)