Skip to content

Commit

Permalink
removed example.py, etc
Browse files Browse the repository at this point in the history
  • Loading branch information
edsu committed Oct 3, 2012
1 parent 42cbea3 commit 99ae335
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 12 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ A simplistic JSON to XML converter.
Example
-------

% ./example.py | xmlling --format - > example.xml
% ./json2xml.py tweet.json | xmllint --format - > tweet.xml

5 changes: 0 additions & 5 deletions example.py

This file was deleted.

31 changes: 25 additions & 6 deletions json2xml.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,51 @@
#!/usr/bin/env python

"""
Call json2xml from the command line:
% ./json2xml.py tweet.json tweet | xmllint --format - > tweet.xml
or from a program:
from json2xml import json2xml
print json2xml("tweet.json", tag_name="tweet")
"""

import sys
import json
from xml.etree.ElementTree import TreeBuilder, tostring

def json2xml(filename, tag_name="data"):
"""pass in the path to a JSON filename, and an optional tag
name for the a root element, and get back some XML for the JSON.
"""
json_data = json.loads(open(filename).read())
builder = data2xml(json_data, tag_name=tag_name)
doc = builder.close()
return tostring(doc)
return tostring(doc, encoding='utf-8')

def data2xml(data, tag_name="data", builder=None):
"""pass in a python datastructure and get back a etree TreeBuilder
"""
if builder == None:
builder = TreeBuilder()

t = type(data)

if t in (str, unicode, int, float, bool):
builder.start(tag_name, {})
builder.data(unicode(data))
builder.end(tag_name)

elif t == list:
for value in data:
data2xml(value, tag_name=tag_name, builder=builder)

elif t == dict:
builder.start(tag_name, {})
for key, value in data.items():
data2xml(value, tag_name=key, builder=builder)
builder.end(tag_name)

return builder

if __name__ == "__main__":
filename = sys.argv[1]
tag_name = len(sys.argv) > 1 ? sys.argv[2] : "data"
print json2xml(filename, tag_name=tag_name)
File renamed without changes.
File renamed without changes.

0 comments on commit 99ae335

Please sign in to comment.