簡體   English   中英

為什么我收到錯誤“類型錯誤:字符串索引必須是整數”

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

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

我需要幫助來理解為什么我會收到錯誤以及如何修復它。

最終,問題是遍歷 dict 會為您提供密鑰。

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

還要考慮檢查 id 是字符串還是整數。 isinstance(s, str)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM