您好我正在尝试解析从android发送的django中的JSON数组 从android发送的json响应看起来像
[{"record":[{"intensity":"Low","body_subpart":"Scalp","symptom":"Agitation"}]}]
现在我在django中的功能如下:
record = simplejson.loads(request.POST['record'])
for o in record:
new_symptoms=UserSymptoms(health_record=new_healthrecord,body_subpart=o.body_subpart,symptoms=o.symptom,intensity=o.intensity)
new_symptoms.save()
但它不起作用 给我发错误 为此,我也尝试在python shell
中执行上面的行>>>rec=json.loads('[{"intensity":"Low","body_subpart":"Scalp","symptom":"Agitation"},{"intensity":"High","body_subpart":"Scalp","symptom":"Bleeding"}]')
>>> for o in rec:
... print rec.body_subpart
...
Traceback (most recent call last):
File "<console>", line 2, in <module>
AttributeError: 'list' object has no attribute 'body_subpart'
答案 0 :(得分:0)
>>>rec=json.loads('[{"intensity":"Low","body_subpart":"Scalp","symptom":"Agitation"},{"intensity":"High","body_subpart":"Scalp","symptom":"Bleeding"}]')
>>> for o in rec:
... print rec['body_subpart']
默认情况下,JSON对象转换为Python dict
,因此令人惊讶的是您以这种方式管理访问其值的原因:
record = simplejson.loads(request.POST['record'])
for o in record:
body_subpart=o.body_subpart
答案 1 :(得分:0)
您必须使用o['body_subpart']
代替o.body_subpart
。虽然这在Javascript中是相同的,但它在Python中是不同的。