-
Notifications
You must be signed in to change notification settings - Fork 0
/
xml2json.py
79 lines (59 loc) · 2.67 KB
/
xml2json.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import xmltodict
import sys
import os
import json
def main():
if len(sys.argv) < 2 or sys.argv[1] not in ["--toxml", "--tojson", "-x", "-j"]:
print("""Usage:
python xml2json.py --toxml|--tojson|-x|-j file|directory
Converts a given XML file or all XML files in a given force-app dir to JSON, or vice-versa. The original XML files are not deleted. JSON files are only converted to XML if a corresponding XML file exists in the same directory. In other words, only JSON files which were generated by this tool will be converted back to XML files.
Arguments:
-j, --tojson: Converts all XML files to JSON. Does not delete the original XML files.
-x, --toxml: Converts all JSON files with corresponding XML counterparts back to XML, and deletes the JSON file.
file: Path to a file.
directory: Path to force-app directory. It is recommended to run --tojson once followed by --toxml to update the line spacing and indentation first if you are planning to use this tool in a bulk fashion.""")
return
converting_to_xml = sys.argv[1] == "--toxml" or sys.argv[1] == "-x"
if len(sys.argv) < 3:
print("Please specify a file or directory")
return
else:
file_or_dir = sys.argv[2]
if os.path.isdir(file_or_dir):
for root, directory, files in os.walk(file_or_dir):
for file in files:
if converting_to_xml:
if file.endswith(".json"):
fullname = os.path.join(root, file)
json_to_xml(fullname)
else:
if file.endswith(".xml"):
fullname = os.path.join(root, file)
xml_to_json(fullname)
else:
if converting_to_xml:
json_to_xml(file_or_dir)
else:
xml_to_json(file_or_dir)
def json_to_xml(fullname):
if not os.path.isfile(fullname[:-5] + ".xml"):
print(f'Ignoring {fullname} since no xml file exists')
return False
print(f'Converting {fullname}.')
with open(fullname, 'r') as f:
json_string = f.read()
xml_string = xmltodict.unparse(json.loads(json_string), pretty=True, encoding='UTF-8', indent=' ')
with open(fullname[:-5] + ".xml", 'w') as f:
f.write(xml_string)
os.remove(fullname)
return True
def xml_to_json(fullname):
print(f'Converting {fullname}.')
with open(fullname, 'r') as f:
xml_string = f.read()
json_string = json.dumps(xmltodict.parse(xml_string), indent=4)
with open(fullname[:-4] + ".json", 'w') as f:
f.write(json_string)
return True
if __name__ == "__main__":
main()