Home > database >  Python 3 - transform Form to nested json
Python 3 - transform Form to nested json

Time:02-26

I am integrating an active campaign with my fastapi endpoint. However when the webhook is called, i get all the fields as a list of tuples. Example:

[
  ("deal[fields][0][id]", 1),
  ("deal[fields][0][key]", "My Custom Field"),
  ("deal[fields][0][value]", "The field value"),
  ("deal[fields][1][id]", 2),
  ("deal[fields][1][key]", "My Other Custom Field"),
  ("deal[fields][1][value]", "The other field value"),
]

And I want to transform it to a json, like the example below:

{
    "deal": {
        "fields": [
            {
                "id": 1,
                "key": "My Custom Field",
                "value": "The field value"
            },
            {
                "id": 2,
                "key": "My Other Custom Field",
                "value": "The other field value"
            }
        ]
    }
}

I'm stuck in how to split, and create this json. I managed only to get a list with the json keys, but couldn't go further

for text, value in [
  ("deal[fields][0][id]", 1),
  ("deal[fields][0][key]", "My Custom Field"),
  ("deal[fields][0][value]", "The field value"),
  ("deal[fields][1][id]", 2),
  ("deal[fields][1][key]", "My Other Custom Field"),
  ("deal[fields][1][value]", "The other field value"),
]:
  filtered_keys = text.split("[")

Any idea / suggestion on how to achieve the result? REGEX is welcomed

EDIT: Updated json to valid, as pointed by scott hunter

CodePudding user response:

res = dict()
res['deal'] = dict()
res['deal']['fields'] = list()


for text, value in [
  ("deal[fields][0][id]", 1),
  ("deal[fields][0][key]", "My Custom Field"),
  ("deal[fields][0][value]", "The field value"),
  ("deal[fields][1][id]", 2),
  ("deal[fields][1][key]", "My Other Custom Field"),
  ("deal[fields][1][value]", "The other field value"),
]:
  filtered_keys = text.split("[")
  if int(filtered_keys[-2][:-1]) == len(res['deal']['fields']):   
     res['deal']['fields'].append(dict())
  res['deal']['fields'][int(filtered_keys[-2][:-1])][filtered_keys[-1][:-1]] = value

I think this should work.

  • Related