Skip to content

Commit 143aa6f

Browse files
committed
fix(json2xml): make it handle top-level keys
It can now handle multiple of them. However, conversion fails, as the bloody xml converter can't handle booleans ??? WTF
1 parent eebcf54 commit 143aa6f

1 file changed

Lines changed: 36 additions & 22 deletions

File tree

etc/xml2json.py renamed to etc/json2xml.py

Lines changed: 36 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -124,27 +124,41 @@ def internal_to_elem(pfsh, factory=ET.Element):
124124
text = None
125125
tail = None
126126
sublist = []
127-
tag = list(pfsh.keys())
128-
if len(tag) != 1:
129-
raise ValueError("Illegal structure with multiple tags: %s" % tag)
130-
tag = tag[0]
131-
value = pfsh[tag]
132-
if isinstance(value, dict):
133-
for k, v in list(value.items()):
134-
if k[:1] == "@":
135-
attribs[k[1:]] = v
136-
elif k == "#text":
137-
text = v
138-
elif k == "#tail":
139-
tail = v
140-
elif isinstance(v, list):
141-
for v2 in v:
142-
sublist.append(internal_to_elem({k: v2}, factory=factory))
143-
else:
144-
sublist.append(internal_to_elem({k: v}, factory=factory))
145-
else:
146-
text = value
147-
e = factory(tag, attribs)
127+
tags = list(pfsh.keys())
128+
129+
# workaround 'cannot convert boolean error'
130+
def sani_value(v):
131+
if v == u'true':
132+
return '1'
133+
elif v == u'false':
134+
return '0'
135+
return v
136+
137+
# Allow deeply nested structures
138+
for tag in tags:
139+
value = pfsh[tag]
140+
# we santize values automatically
141+
# $ref -> _ref
142+
if tag.startswith('$'):
143+
tag = '_' + tag[1:]
144+
145+
if isinstance(value, dict):
146+
for k, v in value.items():
147+
if k[:1] == "@":
148+
attribs[k[1:]] = v
149+
elif k == "#text":
150+
text = v
151+
elif k == "#tail":
152+
tail = v
153+
elif isinstance(v, list):
154+
for v2 in v:
155+
sublist.append(internal_to_elem({k: v2}, factory=factory))
156+
else:
157+
sublist.append(internal_to_elem({k: v}, factory=factory))
158+
else:
159+
text = sani_value(value)
160+
e = factory(tag, attribs)
161+
148162
for sub in sublist:
149163
e.append(sub)
150164
e.text = text
@@ -206,7 +220,7 @@ def main():
206220
prog='xml2json',
207221
usage='%prog -t xml2json -o file.json [file]'
208222
)
209-
p.add_option('--type', '-t', help="'xml2json' or 'json2xml'", default="xml2json")
223+
p.add_option('--type', '-t', help="'xml2json' or 'json2xml'", default="json2xml")
210224
p.add_option('--out', '-o', help="Write to OUT instead of stdout")
211225
p.add_option(
212226
'--strip_text', action="store_true",

0 commit comments

Comments
 (0)