为什么会出现错误“ TypeError:字符串索引必须为整数”

时间:2019-02-14 19:17:31

标签: json python-3.x

我下面有JSON文件,但出现错误

Traceback (most recent call last):
  File "test11.py", line 10, in <module>
    print(driver['id'])
TypeError: string indices must be integers
{"drivers": 
    [
        {
            "id": "91907", 
            "groupId": "9039", 
            "vehicleId": "11111", 
            "currentVehicleId": "11111", 
            "username": "ablahblah", 
            "name": "Andrew Blahblah"
        }
    ]
}

我编写了以下代码以从中提取值 文件

import json
from pprint import pprint

with open('driver.json', 'r') as f:
    drivers_dict = json.load(f)

for driver in drivers_dict:
    print(driver['id'])
    print(driver['groupId'])
    print(driver['vehicleId'])
    print(driver['username'])
    print(driver['name'])

我需要帮助以了解为什么会收到错误以及如何解决该错误。

2 个答案:

答案 0 :(得分:1)

最终,问题在于遍历字典会为您提供密钥。

>>> [i for i in drivers_dict]
['drivers']

我认为您只是混淆了json布局。这有效:

import json

with open('driver.json') as f:
    j = json.load(f)

drivers_list = j["drivers"]

for driver in drivers_list:
    # BTW you can DRY this part:
    for key in ['id', 'groupId', 'vehicleId', 'username', 'name']:
        print(driver[key])

答案 1 :(得分:0)

还可以考虑检查id是字符串还是整数。 isinstance(s, str)