XML to JSON python script (Also JSON to XML)

Here are 2 python scripts which convert XML to JSON and JSON to XML.

XML to JSON

Create the sample XML file, with the below contents.

sample.xml
<planets>
	<planet>
		<name>
			Earth
		</name>
		<radius>
			6,371km
		</radius>
	</planet>
	<planet>
		<name>
			Jupiter
		</name>
		<radius>
			69,911km
		</radius>
	</planet>
	<planet>
		<name>
			Mars
		</name>
		<radius>
			3,390km
		</radius>
	</planet>
</planets>

Run the below python script and and it will output the converted XML as a file named output.json.

import json
import xmltodict

with open("sample.xml", 'r') as f:
	xmlString = f.read()

print("XML input (sample.xml):")
print(xmlString)
	
jsonString = json.dumps(xmltodict.parse(xmlString), indent=4)

print("\nJSON output(output.json):")
print(jsonString)

with open("output.json", 'w') as f:
	f.write(jsonString)

JSON to XML

Create the sample JSON file, with the below contents.

sample.json
{
    "planets": {
        "planet": [
            {
                "name": "Earth",
                "radius": "6,371km"
            },
            {
                "name": "Jupiter",
                "radius": "69,911km"
            },
            {
                "name": "Mars",
                "radius": "3,390km"
            }
        ]
    }
}

Run the below python script and and it will output the converted JSON as a file named output.xml.

import json
import xmltodict

with open('sample.json', 'r') as f:
	jsonString = f.read()

print('JSON input (sample.json):')
print(jsonString)

xmlString = xmltodict.unparse(json.loads(jsonString), pretty=True)

print('\nXML output(output.xml):')
print(xmlString)

with open('output.xml', 'w') as f:
	f.write(xmlString)

You may need to install the xmltodict module:

pip install xmltodict