1👍
✅
There is no standard library nor Django utility function for this.
We can implement convert_form_dict_to_json_dict
as such:
- Initialise
json_dict
to an empty dict{}
. - For each
form_key
, using the example'data[merges][EMAIL]'
,- Use regex to obtain
nested_keys
, i.e.('data', 'merges', 'EMAIL')
. - Determine
last_nesting_level
, i.e.2
from nesting levels(0, 1, 2)
. - Initialise
current_dict
tojson_dict
. - For each
nesting_level, current_key
, i.e.0, 'data'
,1, 'merges'
,2, 'EMAIL'
,- If it is before
last_nesting_level
, get nextcurrent_dict
usingcurrent_key
. - Else, set
current_dict
entry forcurrent_key
tovalue
.
- If it is before
- Use regex to obtain
- Return
json_dict
.
import re
def convert_form_dict_to_json_dict(form_dict):
json_dict = {}
for form_key, value in form_dict.items():
nested_keys = (re.match(r'\w+', form_key).group(0), *re.findall(r'\[(\w+)]', form_key))
last_nesting_level = len(nested_keys) - 1
current_dict = json_dict
for nesting_level, current_key in enumerate(nested_keys):
if nesting_level < last_nesting_level:
current_dict = current_dict.setdefault(current_key, {})
else:
current_dict[current_key] = value
return json_dict
Usage:
POST_dict = {
'type': 'profile',
'fired_at': '2021-05-25 18:03:23',
'data[id]': 'abcd1234',
'data[email]': 'test@domain.com',
'data[email_type]': 'html',
'data[ip_opt]': '0.0.0.0',
'data[web_id]': '1234',
'data[merges][EMAIL]': 'test@domain.com',
'data[merges][FNAME]': 'first_name',
'data[merges][LNAME]': 'last_name',
'data[list_id]': '5678'
}
from pprint import pprint
pprint(convert_form_dict_to_json_dict(POST_dict))
Source:stackexchange.com