Python raises TypeError: string indices must be integers when you attempt to index or key into a str object using a string key (like data["name"]) instead of an integer index or slice (like data[0] or data[0:4])—most commonly because a JSON payload, API response, or CSV row was loaded as a raw unparsed str rather than a parsed dict. Resolve it by parsing the JSON string into a dictionary with json.loads() (or response.json()) before accessing string keys, or by indexing the string with integer positions.
Basic Example
import json
raw_payload = '{"user": "Alice", "role": "admin"}'
# WRONG: 'raw_payload' is still a str, so indexing with key "user" raises TypeError
# print(raw_payload["user"])
# -> TypeError: string indices must be integers, not 'str'
# 1. FIX A: Parse the JSON string into a Python dict first using json.loads()
parsed_data = json.loads(raw_payload)
print(parsed_data["user"]) # Output: "Alice"
# 2. FIX B: If you intentionally want characters from a string, use integer indices or slices
word = "Python"
print(word[0]) # Output: "P"
print(word[0:3]) # Output: "Pyt"
Key Details & Common Scenarios
- 1. Unparsed or double-encoded JSON from APIs / files (
json.loads()):- Accessing
response.text["id"]on arequestsHTTP response fails because.textis astr; callresponse.json()["id"]instead. - Double-encoded JSON: Sometimes an API or database returns JSON wrapped inside a JSON string (
'"{\\"id\\": 42}"'). Callingjson.loads()once returns astr, sodata["id"]still raisesTypeError: string indices must be integers. Checkisinstance(data, str)and calljson.loads(data)a second time if needed.
- Accessing
- 2. Iterating directly over a dictionary instead of
.values()or.items(): Loopingfor item in my_dict:yields the dictionary’s keys (which are usuallystrobjects), not the nested sub-dictionaries:users = { "u1": {"name": "Alice", "age": 30}, "u2": {"name": "Bob", "age": 25}, } # WRONG: 'u' is the key string ("u1"), not the inner dict # for u in users: # print(u["name"]) # TypeError: string indices must be integers # FIX: Iterate over .values() or .items() for user_info in users.values(): print(user_info["name"]) - 3. Iterating over a string instead of a list of dictionaries: If a variable expected to be a
list[dict](such as[{"id": 1}, {"id": 2}]) accidentally holds a singlestr(like"error"), loopingfor row in records: print(row["id"])assigns single characters ("e","r", …) torowand crashes onrow["id"]. Inspecttype(records)before looping. - 4. Reading CSV files with
csv.readerinstead ofcsv.DictReader:csv.readeryields each row as alist[str](or a singlestrif iterated over a line), requiring integer indices (row[0]). Usecsv.DictReader(file)if you want to access columns by header name (row["email"]).
Common Causes & Targeted Fixes Reference
| Scenario / Broken Code | Why obj Is a str |
Resolution |
|---|---|---|
raw = '{"a": 1}'; raw["a"] |
Raw JSON text was never deserialized into a dict |
Parse first: data = json.loads(raw); data["a"] |
resp = requests.get(url); resp.text["a"] |
.text returns the HTTP body as a str |
Use resp.json()["a"] |
for k in my_dict: k["subkey"] |
Iterating a dict yields its string keys, not its values |
Iterate for v in my_dict.values(): v["subkey"] |
data = json.loads(double_json); data["a"] |
JSON string was serialized twice ("\"{\\\"a\\\": 1}\"") |
Decode again if isinstance(data, str): data = json.loads(data) |
for row in csv.reader(f): row["col"] |
csv.reader yields positional lists, not key-value mappings |
Switch to csv.DictReader(f) or index by integer row[0] |
You must log in or register to comment.