【问题标题】:Python & JSON Parsing. TypeError: list indices must be integers, not strPython 和 JSON 解析。 TypeError:列表索引必须是整数,而不是 str
【发布时间】:2014-02-23 12:05:55
【问题描述】:

我完全是 Python 和编程的业余爱好者。我正在尝试从服务器上的 JSON 数据文件中读取数据列表。它会产生以下错误:

TypeError: list indices must be integers, not str

我相信它可以追溯到需要某种改变的声明,但我不知道它应该是什么。

def grabDeviceIDs():
    devices=[];
    ## parse the list
    for deviceListJSON in (getDeviceListFromserver()['mobile_device_group']['mobile_devices']['mobile_device']):
        d = Device()
        d.id = deviceListJSON.get('id')
        devices.append(d)  
    print "Found " + str(len(devices)) + " devices."
    return devices

有什么想法吗?

【问题讨论】:

  • 你能发布一个返回的json的例子吗?
  • 你的结构中有一个你认为有字典的列表。我们需要看看结构。
  • 具体来说,mobile_devices 键听起来好像它会引用一个列表。
  • 当然这是一个示例输出... {'mobile_device_group': {'name': 'Bla'}, 'mobile_devices': [{'name': 'deviceA', 'udid': 'xxx8f9c0ac13df3113c998763d2246b8a392aca8' , 'id': 50}, {'name': 'deviceB', 'udid': 'xxxf4e984ec848608650e1a039a80ed069d37a3b', 'id': 72}],'id': 555}}
  • mobile_devices 是一个列表;包含的字典都没有mobile_device 键。

标签: python json


【解决方案1】:

你的一把钥匙太多了;这应该足够了:

for deviceListJSON in getDeviceListFromserver()['mobile_device_group']['mobile_devices']:

【讨论】:

    猜你喜欢
    • 2014-09-02
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多