json – How can I convert a Python dictionary to an XML string and back while preserving the structure exactly?

I have a need to convert some json to xml and then back to json ideally preserving the structure. I’ve gotten quite close but I can’t find a way to use dicttoxml/xmltodict to not end up with each list of dictionaries being a dictionary with the key ‘item’ and the original dictionary it’s value.

e.g.

{'mydicts': [{'id': 1, 'name': 'alice'}]}

becomes:

1alice

ends up as:

{'mydicts': [{'item': {'id': '1', 'name': 'alice'}}]}

I had to use force_list as well originally. My last resort will be some post-processing code to make this change but I’d prefer to avoid that. Here is some sample code of what I have now:

import xmltodict
import dicttoxml

original_json = {
    "mydicts": [
        {
            "id": 1,
            "name": "alice"
        }
    ]
}


xml_string = dicttoxml.dicttoxml(original_json, attr_type=False).decode()

new_json = xmltodict.parse(xml_string, xml_attribs=False, force_list={'mydicts'})['root']

print(new_json)

Other solutions are perfectly fine as well.

Read more here: Source link