问题描述
最近我开始在python中使用JSON。现在我通过一个post请求传递一个JSON字符串到Python(Django)。现在我想解析/迭代该数据。但是我找不到一个优雅的方式来解析这些数据,这在某种程度上我确实存在。 data = request .POST ['postformdata']
打印数据
{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}'}
这是预期的。但是现在,当我想要获得价值观时,我开始遇到问题。我必须做一些像
mydecoder = json.JSONDecoder()
部分在mydecoder.decode(数据) :
打印部分
#c1r2 c1r1 c2r1,//也期待值
我希望得到值+键,而不是键。现在,我必须使用这些键来获取值,例如
print jdata [key]
如何以更简单的方式迭代这些数据,以便我可以迭代键值,值?
要迭代键值和值,可以写
为key,value在jdata.iteritems()中:
print key,value
您可以在这里阅读文档:
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
这篇关于在Python中解析JSON字符串/对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!