Similar to this answer, I have a nested array structure being submitted by a form to Flask.
However, my values can sometimes come from a multiselect dropdown (several values) and othertimes not, so I may need to parse them one step further with getlist but not always.
Here is an example of request.form
:
ImmutableMultiDict([('name', 'sadfsdaf'), ('description', ''), ('step_action[0]', 'forward'), ('step_values[0]', 'North America'), ('step_values[0]', 'South America')])
Notice how there are two values for step_values[0]
.
Normally, you would access these elements with:
request.form.getlist('step_values[0]')
I found a helper method to parse the POSTed data into a nested array structure, but it doesn't support calling getlist
if there are multiple values.
Helper Method:
def parse_multi_form(form):
"""Returns a dictionary containing complex (multi-dimensional) form data."""
"""https://stackoverflow.com/a/49819417/12718345"""
data = {}
for url_k in form:
v = form[url_k]
ks = []
while url_k:
if '[' in url_k:
k, r = url_k.split('[', 1)
ks.append(k)
if r[0] == ']':
ks.append('')
url_k = r.replace(']', '', 1)
else:
ks.append(url_k)
break
sub_data = data
for i, k in enumerate(ks):
if k.isdigit():
k = int(k)
if i + 1 < len(ks):
if not isinstance(sub_data, dict):
break
if k in sub_data:
sub_data = sub_data[k]
else:
sub_data[k] = {}
sub_data = sub_data[k]
else:
if isinstance(sub_data, dict):
sub_data[k] = v
return data
Output:
{
'name': 'sadfsdaf',
'description': '',
'step_action': {
0: 'forward'
},
'step_values': {
0: 'North America'
}
}
How can I modify the output to support multiple values under a single key, like this?
{
'name': 'sadfsdaf',
'description': '',
'step_action': {
0: 'forward'
},
'step_values': {
0: ['North America', 'South America']
}
}
Note the addition of South America
under 'step_values'[0]
above.