Modelesq Modelesq - 1 year ago 67
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)

Right now it prints as follows:

{"item_data[username]": "johndoe", "item_data[email]": "",...

i just need it to print like so:

"username": "johndoe",
"email": "",

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

nwk nwk
Answer Source

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

data = json.dumps(item_data)


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