-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
51 lines (35 loc) · 1.32 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import xmltodict
import dicttoxml
import json
import sys
__author__ = "marcioz98"
__license__ = "MIT"
__version__ = "0.1.0"
def json2xml(filename):
"""Function that converts json files to xml files"""
print("Converting {}...".format(filename), end="")
with open(filename, "r") as input_file:
xmlstring = json.loads(input_file.read())
xmlstring = dicttoxml.dicttoxml(xmlstring, attr_type=False)
with open("converted_" + filename.replace(".json", ".xml"), "w") as output_file:
output_file.write(str(xmlstring, "utf-8"))
print("...done!")
def xml2json(filename):
"""Function that converts xml files to json files"""
print("Converting {}...".format(filename), end="")
with open(filename, "r") as input_file:
jsonstring = xmltodict.parse(input_file.read())
jsonstring = json.dumps(jsonstring)
with open("converted_" + filename.replace(".xml", ".json"), "w") as output_file:
output_file.write(jsonstring)
print("...done!")
if __name__ == "__main__":
# Parse all program arguments at runtime
for arg in sys.argv[1:]:
ext = arg.split(".")[len(arg.split("."))-1]
if ext == "json":
json2xml(arg)
elif ext == "xml":
xml2json(arg)
else:
print("Cannot convert file {}!".format(arg))