Parsing a string / JSON object in Python

I recently started working with JSON in python. Now I am passing the JSON string to Python (Django) through an email request. Now I want to parse / repeat this data. But I can’t find an elegant way to parse this data, that somehow I’m sure it 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'm starting to run into problems. I should 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, not just the key. Now I have to use the keys to get the values ​​using something like

 print jdata[key] 

How to number this data in a simpler way so that I can iterate over keys, values?

+4
source share
2 answers

To iterate the key and value, you can write

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

You can read the document here: dict.iteritems

+5
source

Just for others to help. In Python3, dict.iteritems() was renamed to dict.iter()

0
source

Source: https://habr.com/ru/post/1343582/


All Articles