[Answered ]-Parse Nested Url Encoded Data from POST Request

1👍

There is no standard library nor Django utility function for this.

We can implement convert_form_dict_to_json_dict as such:

  1. Initialise json_dict to an empty dict {}.
  2. For each form_key, using the example 'data[merges][EMAIL]',
    1. Use regex to obtain nested_keys, i.e. ('data', 'merges', 'EMAIL').
    2. Determine last_nesting_level, i.e. 2 from nesting levels (0, 1, 2).
    3. Initialise current_dict to json_dict.
    4. For each nesting_level, current_key, i.e. 0, 'data', 1, 'merges', 2, 'EMAIL',
      1. If it is before last_nesting_level, get next current_dict using current_key.
      2. Else, set current_dict entry for current_key to value.
  3. 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))
👤aaron

Leave a comment