简体   繁体   中英

How to populate JSON dump from a form to a django template?

I am importing POST request from a form template.html to my view.py by using

data=json.dumps(request.POST)

The data at view.py is in this format:

{"5": "25", "4": "28", "6": "21"}

While running any dictionary syntax on it, the error pops as this data is in a string form. How do convert this to a dictionary? Further, I need to populate the 'key' and 'value' of this dictionary to a template.

Please help me out?

You don't need to do json.dumps(request.POST) , request.POST will be a dictionary.

If you are posting json values in request body, you will have to do json.loads(request.body)

Try this:

>>> a = '{"5": "25", "4": "28", "6": "21"}'
>>> type(a)
<type 'str'>
>>> 
>>> import ast
>>> x = ast.literal_eval(a)
>>> type(x)
<type 'dict'>
>>> 
>>> x.keys()
['5', '4', '6']
>>> x.values()
['25', '28', '21']

This is a json object, it's not yet a dictionary.

https://docs.python.org/2/library/json.html (2.7)

https://docs.python.org/3.4/library/json.html (3.4)

the documentation shows you how to handle json. you can just parse it and access keys to get the values as you are used to!

data_dict = json.loads(data)
print(data_dict['5'])
> "25"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM