forked from hay/xml2json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xml2json.py
executable file
·197 lines (153 loc) · 5.59 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#!/usr/bin/env python
"""xml2json.py Convert XML to JSON
Relies on ElementTree for the XML parsing. This is based on
pesterfish.py but uses a different XML->JSON mapping.
The XML->JSON mapping is described at
http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html
Rewritten to a command line utility by Hay Kranen < github.com/hay >
XML JSON
<e/> "e": null
<e>text</e> "e": "text"
<e name="value" /> "e": { "@name": "value" }
<e name="value">text</e> "e": { "@name": "value", "#text": "text" }
<e> <a>text</a ><b>text</b> </e> "e": { "a": "text", "b": "text" }
<e> <a>text</a> <a>text</a> </e> "e": { "a": ["text", "text"] }
<e> text <a>text</a> </e> "e": { "#text": "text", "a": "text" }
This is very similar to the mapping used for Yahoo Web Services
(http://developer.yahoo.com/common/json.html#xml).
This is a mess in that it is so unpredictable -- it requires lots of testing
(e.g. to see if values are lists or strings or dictionaries). For use
in Python this could be vastly cleaner. Think about whether the internal
form can be more self-consistent while maintaining good external characteristics
for the JSON.
Look at the Yahoo version closely to see how it works. Maybe can adopt
that completely if it makes more sense...
R. White, 2006 November 6
"""
import xml.etree.cElementTree as ET
import simplejson, optparse, sys, os
def elem_to_internal(elem,strip=1):
"""Convert an Element into an internal dictionary (not JSON!)."""
d = {}
for key, value in elem.attrib.items():
d['@'+key] = value
# loop over subelements to merge them
for subelem in elem:
v = elem_to_internal(subelem,strip=strip)
tag = subelem.tag
value = v[tag]
try:
# add to existing list for this tag
d[tag].append(value)
except AttributeError:
# turn existing entry into a list
d[tag] = [d[tag], value]
except KeyError:
# add a new non-list entry
d[tag] = value
text = elem.text
tail = elem.tail
if strip:
# ignore leading and trailing whitespace
if text: text = text.strip()
if tail: tail = tail.strip()
if tail:
d['#tail'] = tail
if d:
# use #text element if other attributes exist
if text: d["#text"] = text
else:
# text is the value if no attributes
d = text or None
return {elem.tag: d}
def internal_to_elem(pfsh, factory=ET.Element):
"""Convert an internal dictionary (not JSON!) into an Element.
Whatever Element implementation we could import will be
used by default; if you want to use something else, pass the
Element class as the factory parameter.
"""
attribs = {}
text = None
tail = None
sublist = []
tag = pfsh.keys()
if len(tag) != 1:
raise ValueError("Illegal structure with multiple tags: %s" % tag)
tag = tag[0]
value = pfsh[tag]
if isinstance(value,dict):
for k, v in value.items():
if k[:1] == "@":
attribs[k[1:]] = v
elif k == "#text":
text = v
elif k == "#tail":
tail = v
elif isinstance(v, list):
for v2 in v:
sublist.append(internal_to_elem({k:v2},factory=factory))
else:
sublist.append(internal_to_elem({k:v},factory=factory))
else:
text = value
e = factory(tag, attribs)
for sub in sublist:
e.append(sub)
e.text = text
e.tail = tail
return e
def elem2json(elem, strip=1):
"""Convert an ElementTree or Element into a JSON string."""
if hasattr(elem, 'getroot'):
elem = elem.getroot()
return simplejson.dumps(elem_to_internal(elem,strip=strip))
def json2elem(json, factory=ET.Element):
"""Convert a JSON string into an Element.
Whatever Element implementation we could import will be used by
default; if you want to use something else, pass the Element class
as the factory parameter.
"""
return internal_to_elem(simplejson.loads(json), factory)
def xml2json(xmlstring,strip=1):
"""Convert an XML string into a JSON string."""
elem = ET.fromstring(xmlstring)
return elem2json(elem,strip=strip)
def json2xml(json, factory=ET.Element):
"""Convert a JSON string into an XML string.
Whatever Element implementation we could import will be used by
default; if you want to use something else, pass the Element class
as the factory parameter.
"""
elem = internal_to_elem(simplejson.loads(json), factory)
return ET.tostring(elem)
def main():
p = optparse.OptionParser(
description = 'Converts XML to JSON or the other way around',
prog = 'xml2json',
usage = '%prog -t xml2json -f file.json file.xml'
)
p.add_option('--type', '-t', help="'xml2json' or 'json2xml'")
p.add_option('--out', '-o', help="Write to OUT instead of stdout")
options, arguments = p.parse_args()
if arguments :
# check if this file exists
if os.path.isfile(arguments[0]) :
input_name = arguments[0]
else :
sys.exit(-1)
else:
p.print_help()
sys.exit(-1)
input = open(input_name).read()
if (options.type == "xml2json") :
out = xml2json(input, strip = 0)
else:
out = json2xml(input)
if (options.out) :
file = open(options.out, 'w')
file.write(out)
file.close()
else:
print out
if __name__ == "__main__":
main()