【问题标题】:Parsing JSON with Python Requests for Django App使用 Django 应用程序的 Python 请求解析 JSON
【发布时间】:2014-01-13 05:11:30
【问题描述】:

我无法解析此请求。它看起来像这样:

{"randomnumber": {"id":blah, "name":blah, ... }, "randomnumber22": { ... }}

使用 python 请求,我检索返回该数据的 url,并对其进行解码,以便尝试遍历字段。然后我得到了类似的东西:

{u'randomnumber': {u'id':u'blah', ... }, u'randomnumber22': { .. }}

当我尝试使用 for 循环浏览数据时,它抱怨我需要使用数字作为字符串索引。我该如何正确处理这个问题?

我的简化代码:

import requests
network = requests.get('http://example.com')
networkoffers = network.json()
for offers in networkoffers:
    offer['name']

所以我正在尝试访问网络['randomnumber']['name'],按照我最初的请求数据示例。

【问题讨论】:

    标签: python django json python-requests


    【解决方案1】:

    您正在遍历字典的键,因此您需要在 for 循环中考虑这一点,如下所示:

    for offer in networkoffers:  # will look through keys, which are strings and not dicts
        networkoffers[offer]['name']
    

    networkoffersdictoffers(或 offer,请注意差异)是键(string)。 offers['name'] 对 Python 没有任何意义,因为 offer 是一个字符串。但是networkoffers[offers] 是一个字典(networkoffers 的值)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 2019-01-18
      相关资源
      最近更新 更多