Skip to content

Instantly share code, notes, and snippets.

@altwitt
Created August 18, 2018 18:54
Show Gist options
  • Save altwitt/6fff4dec994d01e2c417fbda6f59670c to your computer and use it in GitHub Desktop.
Save altwitt/6fff4dec994d01e2c417fbda6f59670c to your computer and use it in GitHub Desktop.
Two-way conversion between json and 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)
import json
import xmltodict
with open("/Users/alt.witt/Desktop/contacts.xml", 'r') as f:
xmlString = f.read()
print("XML input (contacts.xml):")
print(xmlString)
jsonString = json.dumps(xmltodict.parse(xmlString), indent=4)
print("\nJSON output(output.json):")
print(jsonString)
with open("contacts.json", 'w') as f:
f.write(jsonString)
'''
import json
import xmltodict
# another one
def convert(xml_file, xml_attribs=True):
with open(xml_file, "rb") as f: # notice the "rb" mode
d = xmltodict.parse(f, xml_attribs=xml_attribs)
return json.dumps(d, indent=4)
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment