Modelesq Modelesq - 6 months ago 10
JSON Question

Convert python dict to json object with formatted keys and values

So i have my dict from my form post

post_dict = dict(request.POST)
item_data = {}

for key, value in post_dict.items():
if 'item_data' in key:
field = key.split('[')[1].replace(']', ' ')
item_data[key] = ' '.join(value)

data = json.dumps(item_data)
print(data)


Right now it prints as follows:

{"item_data[username]": "johndoe", "item_data[email]": "johndoe@gmail.com",...


i just need it to print like so:

{
"username": "johndoe",
"email": "johndoe@gmail.com",
...
}


How can I remove "item_data" and format the key and values appropriately?

nwk nwk
Answer

Use item_data[field] = ... per Tadhg McDonald-Jensen's comment and replace

data = json.dumps(item_data)

with

data = json.dumps(item_data, indent=2, separators=(',', ': '))