【问题标题】:Django: How to iterate List containing DictsDjango:如何迭代包含字典的列表
【发布时间】:2019-01-12 02:37:42
【问题描述】:

我得到 Json 数据,然后将其转换为 python 对象。 代码如下:

    number = request.POST.get('num')
    url = "http://127.0.0.1:9000/findexclusive"
    querystring = {"num":number}
    response = requests.request("GET", url, params=querystring)
    response = response.json()
    response = json.loads(response)
    return render(request,'home.html',{'details':response})

现在我得到了有效的回复。但无法将此数据转换为 html 页面。 我得到的数据如下:

[{u'pk': 1233, u'model': u'details.modelname', u'fields': {a': u'xyz', u'b': u'something', u'c': u'something', u'd': u''}}]

我如何迭代这个。

这些都不起作用:

for data in b[0]:
...     for key,value in data.items:
...         print key
... 
Traceback (most recent call last):
  File "<console>", line 2, in <module>
AttributeError: 'unicode' object has no attribute 'items'
>>> a = data.json()

【问题讨论】:

    标签: django python-2.7 django-templates


    【解决方案1】:

    当您执行 response[0] 时,您已经获得了 dict 项目。所以for data in response[0] 会给你字典键的列表。您可以使用:

    for data in response:
         for key,value in data.items:
             print key
    

    还请注意,您可以删除此行 response = json.loads(response)。因为response = response.json() 已经给你解码的JSON。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-09
      • 2017-10-24
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-19
      相关资源
      最近更新 更多