【问题标题】:parsing json array in django在 django 中解析 json 数组
【发布时间】:2012-04-21 03:06:29
【问题描述】:

您好,我正在尝试在 django 中解析从 android 发送的 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'

【问题讨论】:

  • 为什么是rec.body_subpart 而不是o.body_subpart
  • 抱歉输入错误它的o.body_subpart

标签: android django json


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    >>>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
    

    【讨论】:

      猜你喜欢
      • 2016-09-03
      • 2017-05-15
      • 2017-01-23
      • 2018-03-08
      • 1970-01-01
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多