使用Python解析JSON报错:String indices must be integers 求助
That error pops up when you’re trying to access a string like it’s a dictionary (using a key like "city" instead of an integer index). Let’s walk through how to fix this based on common JSON structures you might be working with.
First, make sure you’ve properly parsed your JSON string into a Python object. If userdata is a raw JSON string (not already a dict/list), convert it first:
import json # Turn JSON string into a usable Python object parsed_data = json.loads(userdata)
Now let’s cover the most likely scenarios for your data:
Scenario 1: Your data is a list of city entries
If parsed_data is a list where each item is a dictionary with a "city" key (like this):
parsed_data = [ {"city": "Concepcion", "country": "Chile"}, {"city": "Buenos Aires", "country": "Argentina"} ]
Extract cities with a simple loop over the list:
cities = [] for entry in parsed_data: # entry is a dictionary, so we can safely access the "city" key cities.append(entry["city"]) print(cities) # Output: ['Concepcion', 'Buenos Aires']
Scenario 2: Your data is a dictionary containing a list of entries
If your JSON is nested under a key (like "locations" or "users"), target that nested list first:
parsed_data = { "locations": [ {"city": "Concepcion", "region": "Biobio"}, {"city": "Buenos Aires", "region": "CABA"} ] }
Loop over the nested list instead of the top-level dictionary:
cities = [] # First access the list under the "locations" key for location in parsed_data["locations"]: cities.append(location["city"]) print(cities) # Output: ['Concepcion', 'Buenos Aires']
Why you were getting the error
Chances are, you accidentally looped over the keys of a dictionary (which are strings) instead of the list of entries. For example, this wrong code would trigger the error:
# Wrong! Loops over the keys of the top-level dict (like "locations") for item in parsed_data: # item is a string (e.g., "locations"), so item["city"] is invalid cities.append(item["city"])
That’s exactly what causes the "String indices must be integers" message—you’re trying to use a key ("city") on a string value ("locations").
内容的提问来源于stack exchange,提问作者robjeiter

