forked from tyleradams/json-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson-to-xml
More file actions
executable file
·58 lines (44 loc) · 1.48 KB
/
json-to-xml
File metadata and controls
executable file
·58 lines (44 loc) · 1.48 KB
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
#!/usr/bin/env python3
import json
import sys
import xmltodict
JSON_FROM_PYTHON_NAMES = {
dict: "object",
list: "array",
int: "Number",
float: "Number",
bool: "Boolean",
None: "null"
}
class InvalidXMLSerializableData(Exception):
pass
class IncompleteIfTreeException(Exception):
pass
def validate_data(data):
if type(data) == dict and len(data.keys()) == 1:
return
# Prefacing \n makes multierror lines easier to read
message = "\n Only a json object with 1 key can be serialized to xml"
if type(data) != dict:
type_name = JSON_FROM_PYTHON_NAMES[type(data)]
if type_name[0] in ["a", "e", "i", "o", "u"]:
message += "\n The inputted json value is not an object, it is an {}".format(
type_name)
else:
message += "\n The inputted json value is not an object, it is a {}".format(
type_name)
elif type(data) == dict and len(data.keys()) != 1:
message += "\n Input object does not have 1 key, it has {} keys".format(
data.keys())
else:
raise Exception(
"The code cannot handle this input, to receive support, please file a bug specifying the input")
raise InvalidXMLSerializableData(message)
def main():
if len(sys.argv) != 1:
print("Usage: json-to-xml")
data = json.load(sys.stdin)
validate_data(data)
print(xmltodict.unparse(data, pretty=True))
if __name__ == "__main__":
main()