json2xml package¶
Submodules¶
json2xml.dicttoxml module¶
- class json2xml.dicttoxml.SerializerConfig(obj: Any, root: bool, custom_root: str, ids: object, attr_type: bool, item_wrap: bool, item_func: Callable[[str], str], cdata: bool, xml_namespaces: dict[str, Any] | None, list_headers: bool, xpath_format: bool, max_output_bytes: int | None = None, indent: str | None = None)[source]¶
Bases:
objectNormalized conversion options shared by the backend selector and this engine.
- attr_type: bool¶
- cdata: bool¶
- custom_root: str¶
- ids: object¶
- indent: str | None¶
- item_func: Callable[[str], str]¶
- item_wrap: bool¶
- list_headers: bool¶
- max_output_bytes: int | None¶
- obj: Any¶
- root: bool¶
- xml_namespaces: dict[str, Any] | None¶
- xpath_format: bool¶
- json2xml.dicttoxml.convert(obj: Any, ids: object, attr_type: bool, item_func: Callable[[str], str], cdata: bool, item_wrap: bool, parent: str = 'root', list_headers: bool = False) str[source]¶
Routes the elements of an object to the right function to convert them based on their data type.
Retained as public API for downstream callers. No code inside this library calls it; conversion goes through the streaming
_append_*functions, which this delegates to so behavior cannot diverge.
- json2xml.dicttoxml.convert_bool(key: str, val: bool, attr_type: bool, attr: dict[str, Any] | None = None, cdata: bool = False) str[source]¶
Converts a boolean into an XML element
- json2xml.dicttoxml.convert_bool_valid_name(key: str, val: bool, attr_type: bool, attr: dict[str, Any]) str[source]¶
Converts a boolean when the caller already validated the key.
- json2xml.dicttoxml.convert_dict(obj: dict[str, Any], ids: object, parent: str, attr_type: bool, item_func: Callable[[str], str], cdata: bool, item_wrap: bool, list_headers: bool = False) str[source]¶
Converts a dict into an XML string.
Retained as public API for downstream callers. No code inside this library calls it; conversion goes through the streaming
_append_*functions, which this delegates to so behavior cannot diverge.
- json2xml.dicttoxml.convert_kv(key: str, val: str | int | float | Number | datetime | date | time, attr_type: bool, attr: dict[str, Any] | None = None, cdata: bool = False) str[source]¶
Converts a number, string, or datetime into an XML element
- json2xml.dicttoxml.convert_kv_valid_name(key: str, val: str | int | float | Number | datetime | date | time, attr_type: bool, attr: dict[str, Any], cdata: bool = False) str[source]¶
Converts a scalar into an XML element when the caller already validated the key.
- json2xml.dicttoxml.convert_list(items: Sequence[Any], ids: object, parent: str, attr_type: bool, item_func: Callable[[str], str], cdata: bool, item_wrap: bool, list_headers: bool = False) str[source]¶
Converts a list into an XML string.
Retained as public API for downstream callers. No code inside this library calls it; conversion goes through the streaming
_append_*functions, which this delegates to so behavior cannot diverge.
- json2xml.dicttoxml.convert_none(key: str, attr_type: bool, attr: dict[str, Any] | None = None, cdata: bool = False) str[source]¶
Converts a null value into an XML element
- json2xml.dicttoxml.convert_none_valid_name(key: str, attr_type: bool, attr: dict[str, Any]) str[source]¶
Converts a null value when the caller already validated the key.
- json2xml.dicttoxml.convert_to_xpath31(obj: Any, parent_key: str | None = None) str[source]¶
Convert a Python object to XPath 3.1 json-to-xml format.
See: https://www.w3.org/TR/xpath-functions-31/#json-to-xml-mapping
- Args:
obj: The object to convert. parent_key: The key from the parent dict (used for key attribute).
- Returns:
str: XML string in XPath 3.1 format.
- json2xml.dicttoxml.dict2xml_str(attr_type: bool, attr: dict[str, Any], item: dict[str, Any], item_func: Callable[[str], str], cdata: bool, item_name: str, item_wrap: bool, parentIsList: bool, parent: str = '', list_headers: bool = False) str[source]¶
Convert a dict into an XML string.
Retained as public API for downstream callers. No code inside this library calls it; conversion goes through the streaming
_append_*functions, which this delegates to so behavior cannot diverge.
- json2xml.dicttoxml.dicttoxml(obj: str | int | float | bool | complex | ~decimal.Decimal | ~fractions.Fraction | ~numbers.Number | ~collections.abc.Sequence[~typing.Any] | ~datetime.datetime | ~datetime.date | ~datetime.time | None | dict[str, ~typing.Any], root: bool = True, custom_root: str = 'root', ids: object = None, attr_type: bool = True, item_wrap: bool = True, item_func: ~collections.abc.Callable[[str], str] = <function default_item_func>, cdata: bool = False, xml_namespaces: dict[str, ~typing.Any] | None = None, list_headers: bool = False, xpath_format: bool = False, max_output_bytes: int | None = None, indent: str | None = None) bytes[source]¶
Converts a python object into XML.
- Parameters:
obj (dict) – dictionary
root (bool) – Default is True specifies wheter the output is wrapped in an XML root element
custom_root – Default is ‘root’ allows you to specify a custom root element.
ids – Default is None any truthy value gives elements unique ids.
attr_type (bool) – Default is True specifies whether elements get a data type attribute.
item_wrap (bool) –
Default is True specifies whether to nest items in array in <item/> Example if True
..code-block:: python
data = {‘bike’: [‘blue’, ‘green’]}
<bike> <item>blue</item> <item>green</item> </bike>
Example if False
..code-block:: python
data = {‘bike’: [‘blue’, ‘green’]}
..code-block:: xml
<bike>blue</bike> <bike>green</bike>’
item_func – items in a list. Default is ‘item’ specifies what function should generate the element name for
cdata (bool) – Default is False specifies whether string values should be wrapped in CDATA sections.
xml_namespaces –
is a dictionary where key is xmlns prefix and value the urn, Default is {}. Example:
{ 'flex': 'http://www.w3.org/flex/flexBase', 'xsl': "http://www.w3.org/1999/XSL/Transform"}
results in
<root xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:flex="http://www.w3.org/flex/flexBase">
list_headers (bool) –
Default is False Repeats the header for every element in a list. Example if True:
"Bike": [ {'frame_color': 'red'}, {'frame_color': 'green'} ]}
results in
<Bike><frame_color>red</frame_color></Bike> <Bike><frame_color>green</frame_color></Bike>
xpath_format (bool) – Default is False When True, produces XPath 3.1 json-to-xml compliant output as specified by W3C (https://www.w3.org/TR/xpath-functions-31/#func-json-to-xml). Uses type-based element names (map, array, string, number, boolean, null) with key attributes and the http://www.w3.org/2005/xpath-functions namespace.
max_output_bytes – Optional exact UTF-8 byte limit enforced while serializing.
indent –
Optional indentation unit, such as two spaces. When given, the serializer emits indented output directly instead of returning compact markup that would have to be reformatted afterwards.
Example:
{"name": "John", "age": 30}
results in
<map xmlns="http://www.w3.org/2005/xpath-functions"> <string key="name">John</string> <number key="age">30</number> </map>
Dictionaries-keys with special char ‘@’ has special meaning: @attrs: This allows custom xml attributes:
{'@attr':{'a':'b'}, 'x':'y'}
results in
<root a="b"><x>y</x></root>
@flat: If a key ends with @flat (or dict contains key ‘@flat’), encapsulating node is omitted. Similar to item_wrap. @val: @attrs requires complex dict type. If primitive type should be used, then @val is used as key. To add custom xml-attributes on a list {‘list’: [4, 5, 6]}, you do this:
{'list': {'@attrs': {'a':'b','c':'d'}, '@val': [4, 5, 6]}
which results in
<list a="b" c="d"><item>4</item><item>5</item><item>6</item></list>
- json2xml.dicttoxml.escape_xml(s: str | int | float | Number | None) str[source]¶
Escape a string for use in XML.
- Args:
s (str | numbers.Number): The string to escape.
- Returns:
str: The escaped string.
- json2xml.dicttoxml.get_unique_id(element: str) str[source]¶
Generate an ID for a given element.
- Args:
element (str): The element to generate an ID for.
- Returns:
str: The generated ID.
- json2xml.dicttoxml.get_xml_type(val: Any) str[source]¶
Get the XML type of a given value.
- Args:
val (ELEMENT): The value to get the type of.
- Returns:
str: The XML type.
- json2xml.dicttoxml.get_xpath31_tag_name(val: Any) str[source]¶
Determine XPath 3.1 tag name by Python type.
See: https://www.w3.org/TR/xpath-functions-31/#func-json-to-xml
- Args:
val: The value to get the tag name for.
- Returns:
str: The XPath 3.1 tag name (map, array, string, number, boolean, null).
- json2xml.dicttoxml.key_is_valid_xml(key: str) bool[source]¶
Check if a key is a valid XML name.
- Args:
key (str): The key to check.
- Returns:
bool: True if the key is a valid XML name, False otherwise.
- json2xml.dicttoxml.key_is_valid_xml_attr(key: str) bool[source]¶
Return True when key can be emitted directly as an XML attribute name.
- json2xml.dicttoxml.list2xml_str(attr_type: bool, attr: dict[str, Any], item: Sequence[Any], item_func: Callable[[str], str], cdata: bool, item_name: str, item_wrap: bool, list_headers: bool = False) str[source]¶
Convert a list into an XML string.
Retained as public API for downstream callers. No code inside this library calls it; conversion goes through the streaming
_append_*functions, which this delegates to so behavior cannot diverge.
- json2xml.dicttoxml.make_attrstring(attr: dict[str, Any]) str[source]¶
Create a string of XML attributes from a dictionary.
- Args:
attr (dict[str, Any]): The dictionary of attributes.
- Returns:
str: The string of XML attributes.
- json2xml.dicttoxml.make_id(element: str, start: int = 100000, end: int = 999999) str[source]¶
Generate a random ID for a given element.
- Args:
element (str): The element to generate an ID for. start (int, optional): The lower bound for the random number. Defaults to 100000. end (int, optional): The upper bound for the random number. Defaults to 999999.
- Returns:
str: The generated ID.
- json2xml.dicttoxml.make_typed_attrstring(attr: dict[str, Any], xml_type: str) str[source]¶
Create XML attributes with a type value without mutating caller attrs.
- json2xml.dicttoxml.make_valid_xml_name(key: str, attr: dict[str, Any]) tuple[str, dict[str, Any]][source]¶
Return a valid XML element name and carry the original key as metadata when needed.
- json2xml.dicttoxml.serialize(config: SerializerConfig) bytes[source]¶
Render an already normalized configuration; see
dicttoxml().
json2xml.json2xml module¶
- class json2xml.json2xml.Json2xml(data: None | bool | int | float | str | list[None | bool | int | float | str | list[JSONValue] | dict[str, JSONValue]] | dict[str, None | bool | int | float | str | list[JSONValue] | dict[str, JSONValue]] = None, wrapper: str = 'all', root: bool = True, pretty: bool = False, attr_type: bool = True, item_wrap: bool = True, xpath_format: bool = False, cdata: bool = False, list_headers: bool = False, max_depth: int = 100, max_items: int = 100000, max_output_bytes: int = 10485760)[source]¶
Bases:
objectConfigure conversion of a decoded JSON value to XML.
- Parameters:
data – The decoded JSON value.
Nonerepresents absent input; other falsy values are serialized.wrapper – The root element name used when
rootis enabled.root – Include the XML declaration and root element.
pretty – Indent serialized XML as it is generated, returning text instead of bytes.
attr_type – Add each value’s JSON type as an XML attribute.
item_wrap – Wrap list members in
<item>elements.xpath_format – Emit the W3C XPath 3.1 JSON-to-XML representation.
cdata – Wrap string values in CDATA sections.
list_headers – Repeat the parent element for nested dictionary items in lists.
max_depth – Maximum JSON container nesting depth.
max_items – Maximum total number of JSON values and containers.
max_output_bytes – Maximum compact or pretty UTF-8 XML size.
- to_xml() bytes | str | None[source]¶
Serialize the configured JSON value.
- Returns:
Pretty-printed XML text when
prettyis enabled, UTF-8 encoded XML bytes otherwise, orNonewhen the configured data isNone.- Raises:
InvalidDataError – If a conversion limit is exceeded or serialization rejects the data.
json2xml.utils module¶
Utility methods for reading JSON data from various sources.
- exception json2xml.utils.InvalidDataError[source]¶
Bases:
ExceptionRaised when the data is invalid.
- exception json2xml.utils.JSONReadError[source]¶
Bases:
ExceptionRaised when there is an error reading JSON data.
- exception json2xml.utils.StringReadError[source]¶
Bases:
ExceptionRaised when there is an error reading from a string.
- exception json2xml.utils.URLReadError[source]¶
Bases:
ExceptionRaised when there is an error reading from a URL.
- json2xml.utils.readfromjson(filename: str) None | bool | int | float | str | list[JSONValue] | dict[str, JSONValue][source]¶
Read JSON data from a file.
- json2xml.utils.readfromstring(jsondata: object) None | bool | int | float | str | list[JSONValue] | dict[str, JSONValue][source]¶
Load JSON data from a string.
- json2xml.utils.readfromurl(url: str, params: dict[str, str] | None = None, *, max_response_bytes: int = 10485760, allow_private_networks: bool = False) None | bool | int | float | str | list[JSONValue] | dict[str, JSONValue][source]¶
Load bounded JSON data from a public URL.
Private-network access is available only through the explicit trusted-caller opt-in. Redirects and embedded credentials are always rejected.
Module contents¶
Top-level package for json2xml.