2012-04-08 151 views
1

你好我试图解析JSON阵列从安卓 从机器人的外观发送类似解析JSON数组

[{"record":[{"intensity":"Low","body_subpart":"Scalp","symptom":"Agitation"}]}] 

JSON响应发送的Django现在我的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() 

,但它不工作 gving我的错误 对于我也尝试执行上面的python外壳线条

>>>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

为什么'rec.body_subpart'而不是'o.body_subpart'? – San4ez 2012-04-08 08:26:37

+0

抱歉打字错误其o.body_subpart – user1163236 2012-04-08 08:47:07

回答

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 
0

必须使用o['body_subpart']代替o.body_subpart。虽然这在Javascript中是相同的,但它在Python中不同。

+0

嘿,谢谢,真的工作... – user1163236 2012-04-08 08:48:36