Here's a generator-based solution with a few nice features:
- Tolerates multiple blank lines between albums in text file
- Tolerates leading/trailing blank lines in text file
- Uses only an album's worth of memory at a time
- Demonstrates a lot of neato things you can do with Python :)
albums.txt
Album title1
song1 title
song1 url
song2 title
song2 url
Album title2
song1 title
song1 url
song2 title
song2 url
Code
from django.utils import simplejson
def gen_groups(lines):
""" Returns contiguous groups of lines in a file """
group = []
for line in lines:
line = line.strip()
if not line and group:
yield group
group = []
elif line:
group.append(line)
def gen_albums(groups):
""" Given groups of lines in an album file, returns albums """
for group in groups:
title = group.pop(0)
songinfo = zip(*[iter(group)]*2)
songs = [dict(title=title,url=url) for title,url in songinfo]
album = dict(title=title, songs=songs)
yield album
input = open('albums.txt')
groups = gen_groups(input)
albums = gen_albums(groups)
print simplejson.dumps(list(albums))
Output
[{"songs": [{"url": "song1 url", "title": "song1 title"}, {"url": "song2 url", "title": "song2 title"}], "title": "song2
title"},
{"songs": [{"url": "song1 url", "title": "song1 title"}, {"url": "song2 url", "title": "song2 title"}], "title": "song2
title"}]
Album information could then be accessed in Javascript like so:
var url = albums[1].songs[0].url;
Lastly, here's a note about that tricky zip line.