I have the JSON file below, and I am getting an error
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.
>>> [i for i in drivers_dict]
['drivers']
I think you just got your json layout confused. 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. isinstance(s, str)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.