I have an HTML form with multiple inputs named like this:
I have a form that has arrays with either one or two levels, so either a[1] or b[1][2].
I've written a regex solution to get this into the dict with posted data.
import re
re_post = re.compile(r'([a-z_]*)(\[(.*?)\])?(\[(.*?)\])?')
for post_key, post_value in request.form.copy().items():
matches = list(re_post.findall(post_key)[0][0::2])
if matches[1]:
request.form.setdefault(matches[0], {})
if matches[2]:
request.form[matches[0]].setdefault(matches[1], {})
request.form[matches[0]][matches[1]][matches[2]] = post_value
else:
request.form[matches[0]][matches[1]] = post_value
else:
continue
del request.form[post_key]
So it iterates over the form keys/values and matches 3 groups in the key: first the 'base' name, and then the names of two levels. If either first or second level name is present, it will create a dictionary and populate it with the posted value and then proceeds to remove the original key/value.