I have a form that submits data to the server that looks like the following:
videos[0][type]=Vimeo&
videos[0][moments][0][time]=11&
videos[0][moments][0][lng]=111&
videos[0][moments][0][lat]=111&
videos[0][moments][1][time]=222&
videos[0][moments][1][lng]=222&
videos[0][moments][1][lat]=222&
videos[1][type]=YouTube&
videos[1][moments][0][time]=111&
videos[1][moments][0][lng]=111&
videos[1][moments][0][lat]=111
...
I am using Flask and I would like to be able to loop through the videos and moments but it seems like there isn't a way to do that. I tried looking for libraries on Google but my Google-fu is weak tonight.
Any suggestions? Thanks!
EDIT: Based on lazy1's answer, I modified his/her code to
def add(root, path, value):
for part in path[:-1]:
root = root.setdefault(part, {})
root[path[-1]] = value
def parse(s):
items = {}
for key, value in parse_qsl(s):
parts = filter(None, re.split('[\[\]]', key))
name = parts[0]
if name not in items:
items[name] = {}
add(items[name], parts[1:], value)
return items
that will generate a hash:
{'map': {'title': 'orange'}, 'videos': {'1': {'moments': {'0': {'lat': '111', 'lng': '111', 'time': '111'}}, 'type': 'YouTube'}, '0': {'moments': {'1': {'lat': '222', 'lng': '222', 'time': '222'}, '0': {'lat': '111', 'lng': '111', 'time': '11'}}, 'type': 'Vimeo'}}}
for a query that looks like:
map[title]=orange&
videos[0][type]=Vimeo&
videos[0][moments][0][time]=11&
videos[0][moments][0][lng]=111&
videos[0][moments][0][lat]=111&
videos[0][moments][1][time]=222&
videos[0][moments][1][lng]=222&
videos[0][moments][1][lat]=222&
videos[1][type]=YouTube&
videos[1][moments][0][time]=111&
videos[1][moments][0][lng]=111&
videos[1][moments][0][lat]=111
...