为什么我收到错误'TypeError:字符串索引必须是整数'

问题描述 投票:1回答:2

我有下面的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'])

我需要帮助才能理解为什么我会收到错误以及如何修复错误。

json python-3.x
2个回答
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])

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.