62 lines
2.4 KiB
Python
Executable File
62 lines
2.4 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
# xml2json — convert simple XML to JSON (attributes as @name, text as #text, repeated tags as arrays).
|
|
# Usage: xml2json [--pretty] input.xml [output.json]
|
|
"""xml2json: XML to JSON with a readable convention. Attributes become `@name`
|
|
keys, element text becomes `#text`, and repeated sibling tags collapse into
|
|
arrays — the standard mapping, done with stdlib xml.etree only."""
|
|
import argparse, json, sys
|
|
import xml.etree.ElementTree as ET
|
|
|
|
def elem_to_json(el):
|
|
d = {}
|
|
for k, v in el.attrib.items():
|
|
d["@" + k] = v
|
|
children = {}
|
|
for child in el:
|
|
v = elem_to_json(child)
|
|
if child.tag in children:
|
|
if not isinstance(children[child.tag], list):
|
|
children[child.tag] = [children[child.tag]]
|
|
children[child.tag].append(v)
|
|
else:
|
|
children[child.tag] = v
|
|
d.update(children)
|
|
text = (el.text or "").strip()
|
|
if text:
|
|
if d: d["#text"] = text
|
|
else: return text
|
|
return d
|
|
|
|
def convert(inp, out, pretty=False):
|
|
tree = ET.parse(inp)
|
|
data = {tree.getroot().tag: elem_to_json(tree.getroot())}
|
|
text = json.dumps(data, indent=2) if pretty else json.dumps(data)
|
|
if out: open(out, "w", encoding="utf-8").write(text + "\n")
|
|
else: sys.stdout.write(text + "\n")
|
|
return 0
|
|
|
|
def selftest():
|
|
import tempfile, os
|
|
with tempfile.TemporaryDirectory() as d:
|
|
x = os.path.join(d, "a.xml")
|
|
open(x, "w").write('<root><item id="1">one</item><item id="2">two</item><meta lang="en">hi</meta></root>')
|
|
o = os.path.join(d, "a.json")
|
|
assert convert(x, o, pretty=True) == 0
|
|
data = json.load(open(o))
|
|
assert data["root"]["item"] == [{"@id": "1", "#text": "one"}, {"@id": "2", "#text": "two"}], data
|
|
assert data["root"]["meta"] == {"@lang": "en", "#text": "hi"}
|
|
print("xml2json selftest: PASS"); return 0
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description="Convert simple XML to JSON (attributes @name, text #text, repeats as arrays).")
|
|
ap.add_argument("input", nargs="?"); ap.add_argument("output", nargs="?")
|
|
ap.add_argument("--pretty", action="store_true")
|
|
ap.add_argument("--selftest", action="store_true")
|
|
a = ap.parse_args()
|
|
if a.selftest: return selftest()
|
|
if not a.input: ap.error("need an input XML file")
|
|
return convert(a.input, a.output, a.pretty)
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|