简体   繁体   English

为什么我收到错误“类型错误:字符串索引必须是整数”

[英]Why am I getting error 'TypeError: string indices must be integers'

I have the JSON file below, and I am getting an error我有下面的 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"
        }
    ]
}

I have written the follow code to extract out values from the file我编写了以下代码来从文件中提取值

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'])

I need help to understand why I am getting the error and how to fix it.我需要帮助来理解为什么我会收到错误以及如何修复它。

Ultimately, the problem is that looping over a dict gives you the keys.最终,问题是遍历 dict 会为您提供密钥。

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

I think you just got your json layout confused.我想你只是把你的 json 布局弄糊涂了。 This works:这有效:

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])

Also Consider checking if the id is string or integer.还要考虑检查 id 是字符串还是整数。 isinstance(s, str)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM