代码之家  ›  专栏  ›  技术社区  ›  Sapna Sharma

Django:如何迭代包含dict的列表

  •  0
  • Sapna Sharma  · 技术社区  · 6 年前

    我获取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()
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   neverwalkaloner    6 年前

    当你这样做的时候 response[0] 你已经得到了dict项目。所以 for data in response[0] 会给你dict的钥匙清单。你可以使用:

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

    另外请注意,您可以删除此行 response = json.loads(response) . 自从 response = response.json() 已经给你解码的JSON了。