简体   繁体   中英

Parsing JSON string/object in Python

I've recently started working with JSON in python. Now I'm passing a JSON string to Python(Django) through a post request. Now I want to parse/iterate of that data. But I can't find a elegant way to parse this data, which somehow I'm pretty sure exists.

data = request.POST['postformdata']
print data
{"c1r1":"{\"Choice\":\"i1\"}","c2r1":"{\"Bool\":\"i2\"}","c1r2":"{\"Chars\":\"i3\"}"}

jdata = json.loads(data)
print jdata
{u'c1r2': u'{"Chars":"i3"}', u'c1r1': u'{"Choice":"i1"}', u'c2r1': u'{"Bool":"i2"}'}

This is what was expected. But now when I want to get the values, I start running into problems. I have to do something like

mydecoder = json.JSONDecoder()
for part in mydecoder.decode(data):                                             
    print part
# c1r2 c1r1 c2r1 ,//Was expecting values as well

I was hoping to get the value + key, instead of just the key. Now, I have to use the keys to get values using something like

print jdata[key]

How do I iterate over this data in a simpler fashion, so that I can iterate over key, values?

To iterate key and value, you can write

for key, value in jdata.iteritems():
    print key, value

You can read the document here: dict.iteritems

Just for others to help. In Python3 dict.iteritems() has been renamed to dict.iter()

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