Skip to content

Instantly share code, notes, and snippets.

@honza
Created February 24, 2012 03:03
Show Gist options
  • Save honza/1896913 to your computer and use it in GitHub Desktop.
Save honza/1896913 to your computer and use it in GitHub Desktop.
Tim Hortons: XML => JSON
"""
Convert an XML list of Tim Hortons restaurant locations to JSON
Usage: python parse.py sourcefile destfile
E.g.: python parse.py locations.xml locations.json
"""
import json
import sys
try:
from pyquery import PyQuery as pq
except ImportError:
print "pip install pyquery"
sys.exit(1)
keys = ['id', 'storeid', 'address1', 'address2', 'city', 'lat', 'lng',
'distance', 'province', 'postal', 'phone', 'timcard', 'instoreseating',
'hrs24', 'coldstone', 'drivethru', 'servicedisruptionflag']
def read_file(fn):
f = open(fn)
data = f.read()
f.close()
return data
def write_file(fn, stuff):
f = open(fn, 'w')
f.write(json.dumps(stuff, indent=4))
f.close()
def parse_marker(xml):
result = {}
for key in keys:
result[key] = xml.get(key)
return result
def main(source, dest):
data = read_file(source)
d = pq(data)
a = d('marker')
array = [parse_marker(x) for x in a]
write_file(dest, array)
if __name__ == '__main__':
try:
source = sys.argv[1]
dest = sys.argv[2]
except KeyError:
print "Usage: python parse.py sourcefile destfile"
print "E.g.: python parse.py locations.xml locations.json"
sys.exit(1)
main(source, dest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment