Created
August 18, 2018 18:54
-
-
Save altwitt/6fff4dec994d01e2c417fbda6f59670c to your computer and use it in GitHub Desktop.
Two-way conversion between json and xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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