2012-04-08 227 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