Python TypeError: String Indices Must Be Integers β How to Fix It
TypeError: string indices must be integers
What causes this
Youβre treating a string like a dictionary. This usually happens when you expect a parsed JSON object (dict) but actually have a raw JSON string, or when youβre iterating over a data structure incorrectly and end up accessing individual characters of a string with a key instead of an index.
Fix 1: Parse your JSON first
The most common cause β you have a JSON string, not a dict:
# β data is still a string
data = '{"name": "Alice", "age": 30}'
print(data['name']) # TypeError!
# β
Parse it into a dict first
import json
data = json.loads('{"name": "Alice", "age": 30}')
print(data['name']) # "Alice"
This also happens with API responses:
import requests
response = requests.get('https://api.example.com/user')
# β response.text is a string
user = response.text
print(user['name']) # TypeError!
# β
Use .json() to parse
user = response.json()
print(user['name']) # Works
Fix 2: Check what youβre iterating over
When you loop over a dict, you get keys (strings). If you then try to index those strings with a key, you get this error:
data = {"users": [{"name": "Alice"}, {"name": "Bob"}]}
# β Iterating over the dict gives you keys, not values
for item in data:
print(item['name']) # item is "users" (a string), not a dict!
# β
Iterate over the list inside the dict
for item in data['users']:
print(item['name']) # Works
Fix 3: Double-check nested structures
Sometimes the data structure isnβt what you expect:
# β data[0] might be a string, not a dict
data = ["Alice", "Bob"]
print(data[0]['name']) # TypeError!
# β
Check the type first
print(type(data[0])) # <class 'str'>
Use type() or isinstance() to debug:
if isinstance(data, str):
data = json.loads(data)
# Now safely access keys
print(data['name'])
Fix 4: File reading issues
Reading a JSON file but forgetting to parse it:
# β read() returns a string
with open('data.json') as f:
data = f.read()
print(data['key']) # TypeError!
# β
Use json.load() (not json.loads())
with open('data.json') as f:
data = json.load(f)
print(data['key']) # Works
Related resources
How to prevent it
- Always use
response.json()instead ofresponse.textwhen working with APIs that return JSON - Use
json.load()for files andjson.loads()for strings β donβt mix them up - When debugging, print
type(variable)before accessing keys to confirm you have a dict - Add type hints to your functions so your editor catches these mistakes early
Related: Pip Install Error Fix