59

I see a number of questions on SO asking about ways to convert XML to JSON, but I'm interested in going the other way. Is there a python library for converting JSON to XML?


Edit: Nothing came back right away, so I went ahead and wrote a script that solves this problem.

Python already allows you to convert from JSON into a native dict (using json or, in versions < 2.6, simplejson), so I wrote a library that converts native dicts into an XML string.

https://github.com/quandyfactory/dict2xml

It supports int, float, boolean, string (and unicode), array and dict data types and arbitrary nesting (yay recursion).

I'll post this as an answer once 8 hours have passed.

2

7 Answers 7

58

Nothing came back right away, so I went ahead and wrote a script that solves this problem.

Python already allows you to convert from JSON into a native dict (using json or, in versions < 2.6, simplejson), so I wrote a library that converts native dicts into an XML string.

https://github.com/quandyfactory/dict2xml

It supports int, float, boolean, string (and unicode), array and dict data types and arbitrary nesting (yay recursion).

Sign up to request clarification or add additional context in comments.

1 Comment

awesome response to actually build (and maintain!) something to resolve a SO question!
20

If you don't have such a package, you can try:

def json2xml(json_obj, line_padding=""):
    result_list = list()

    json_obj_type = type(json_obj)

    if json_obj_type is list:
        for sub_elem in json_obj:
            result_list.append(json2xml(sub_elem, line_padding))

        return "\n".join(result_list)

    if json_obj_type is dict:
        for tag_name in json_obj:
            sub_obj = json_obj[tag_name]
            result_list.append("%s<%s>" % (line_padding, tag_name))
            result_list.append(json2xml(sub_obj, "\t" + line_padding))
            result_list.append("%s</%s>" % (line_padding, tag_name))

        return "\n".join(result_list)

    return "%s%s" % (line_padding, json_obj)

For example:

s='{"main" : {"aaa" : "10", "bbb" : [1,2,3]}}'
j = json.loads(s)
print(json2xml(j))

Result:

<main>
        <aaa>
                10
        </aaa>
        <bbb>
                1
                2
                3
        </bbb>
</main>

2 Comments

It is showing an Unresolved reference error on the recursive call in Python2.7
given s = {'person': {'web': {'email': '[email protected]'}, 'address': {'street1': '123 Bar St', 'street2': '', 'state': 'WI', 'zip': 55555, 'city': 'Madison'}}}. It is giving ` j = json.loads(s) File "/usr/lib/python2.7/json/__init__.py", line 338, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Expecting property name: line 1 column 2 (char 1)`
15

Load it into a dict using json.loads then use anything from this question...

Serialize Python dictionary to XML

Comments

4

Use dicttoxml to convert JSON directly to XML

Installation
pip install dicttoxml
or
easy_install dicttoxml

In [2]: from json import loads

In [3]: from dicttoxml import dicttoxml

In [4]: json_obj = '{"main" : {"aaa" : "10", "bbb" : [1,2,3]}}'

In [5]: xml = dicttoxml(loads(json_obj))

In [6]: print(xml)
<?xml version="1.0" encoding="UTF-8" ?><root><main type="dict"><aaa type="str">10</aaa><bbb type="list"><item type="int">1</item><item type="int">2</item><item type="int">3</item></bbb></main></root>

In [7]: xml = dicttoxml(loads(json_obj), attr_type=False)

In [8]: print(xml)
<?xml version="1.0" encoding="UTF-8" ?><root><main><aaa>10</aaa><bbb><item>1</item><item>2</item><item>3</item></bbb></main></root>

For more information on dicttoxml

1 Comment

this is the same library the user who asked the question wrote..and posted inside the question..........
2

I found xmltodict to be useful. Looks like it was released after some of the posts here. https://pypi.org/project/xmltodict/

import xmltodict
import json
sample_json = {"note": {"to": "Tove", "from": "Jani", "heading": "Reminder", "body": "Don't forget me this weekend!"}}
#############
#json to xml
#############
json_to_xml = xmltodict.unparse(sample_json)
print(json_to_xml)
#############
#xml to json
#############
x_to_j_dict = xmltodict.parse(json_to_xml)
x_to_j_string = json.dumps(x_to_j_dict)
back_to_json = json.loads(x_to_j_string)
print(back_to_json)

Comments

1
from json import loads
from dicttoxml import dicttoxml

s='{"main" : {"aaa" : "10", "bbb" : [1,2,3]}}'
xml = dicttoxml(loads(s))

Or if your data is stored in a pandas data.frame as mine often is:

df['xml'] = df['json'].apply(lambda s: dicttoxml(json.loads(s))

Comments

0

Raw Python code to convert JSON to XML

Let say, JSON data is

json_data = {
'name': 'Your Name',
'age': 27,
'email': '',
'marks': {
    'hindi': 90,
    'math': 90,
    'english': 90,
    'physics': 90,
    'chemistry': None
   }
}

Python code

Import this

import xml.etree.ElementTree as ET

root = ET.Element("root")
def json_to_xml(parent_var, keyname, value):
    new_ele = ET.SubElement(parent_var, keyname)
    if value:
        if isinstance(value, dict):
            for k, v in value.items():
                json_to_xml(new_ele, k, v)
        else:
            new_ele.text = str(value)


for key, value in json_data.items():
    json_to_xml(root, key, value)

tree = ET.ElementTree(root)
# Write to file
tree.write("output.xml", encoding='utf-8', xml_declaration=True)

Final XML is exported in the output.xml file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.