Skip to content

xml2json

XML to JSON conversion utilities for FFprobe output.

Functions:

Name Description
xml_string_to_json

Convert an XML string to a JSON string.

xml_to_dict

Convert an XML Element to a dictionary representation.

xml_string_to_json

xml_string_to_json(xml_string: str) -> str

Convert an XML string to a JSON string.

This function takes an XML string, parses it into an ElementTree structure, converts it to a dictionary using xml_to_dict, and then serializes it to a JSON string.

Parameters:

Name Type Description Default
xml_string str

A string containing valid XML data.

required

Returns:

Type Description
str

A JSON string representation of the XML data, with the root element's tag as the top-level key and the converted dictionary as its value.

Example

xml = "value" xml_string_to_json(xml) '{ "root": { "item": { "text": "value" } } }'

xml_to_dict

xml_to_dict(element: Element) -> dict[str, Any]

Convert an XML Element to a dictionary representation.

This function recursively converts an XML Element and its children into a nested dictionary structure. Attributes are preserved as dictionary keys, and text content is stored under the 'text' key when present.

Parameters:

Name Type Description Default
element Element

The XML Element to convert.

required

Returns:

Type Description
dict[str, Any]

A dictionary representation of the XML Element. - Attributes are stored as key-value pairs - Child elements are stored as nested dictionaries - Multiple elements with the same tag are stored as lists - Text content is stored under the 'text' key