json2xml package

Submodules

json2xml.dicttoxml module

json2xml.dicttoxml.convert(obj: Any, ids: Any, 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

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: list[str], 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.

json2xml.dicttoxml.convert_kv(key: str, val: str | int | float | Number | datetime | date, 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, 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: list[str] | None, 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.

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.default_item_func(parent: str) str[source]
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]

parse dict2xml

json2xml.dicttoxml.dicttoxml(obj: str | int | float | bool | complex | ~decimal.Decimal | ~fractions.Fraction | ~numbers.Number | ~collections.abc.Sequence[~typing.Any] | ~datetime.datetime | ~datetime.date | None | dict[str, ~typing.Any], root: bool = True, custom_root: str = 'root', ids: list[int] | None = 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) 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 (bool) – Default is False specifies whether elements get 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.

    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 a unique ID for a given element.

Args:

element (str): The element to generate an ID for.

Returns:

str: The unique 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.is_primitive_type(val: Any) bool[source]
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]
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.validate_xml_attr_names(attr: dict[str, Any]) None[source]

Reject attributes that would make the generated XML malformed.

json2xml.dicttoxml.wrap_cdata(s: str | int | float | Number) str[source]

Wraps a string into CDATA sections

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 = True, attr_type: bool = True, item_wrap: bool = True, xpath_format: bool = False, cdata: bool = False, list_headers: bool = False)[source]

Bases: object

Wrapper class to convert the data to xml

to_xml() Any | None[source]

Convert to xml using dicttoxml.dicttoxml and then pretty print it.

json2xml.utils module

Utility methods for reading JSON data from various sources.

exception json2xml.utils.InvalidDataError[source]

Bases: Exception

Raised when the data is invalid.

exception json2xml.utils.JSONReadError[source]

Bases: Exception

Raised when there is an error reading JSON data.

exception json2xml.utils.StringReadError[source]

Bases: Exception

Raised when there is an error reading from a string.

exception json2xml.utils.URLReadError[source]

Bases: Exception

Raised 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) None | bool | int | float | str | list[JSONValue] | dict[str, JSONValue][source]

Load JSON data from a URL.

Module contents

Top-level package for json2xml.