Python3解析JSON获取指定值报错:TypeError问题排查
Hey there! Let's break down why you're hitting this error and get your code working to grab that "login" value.
What's Causing the Error?
That TypeError is spelling out the issue clearly: you're trying to use a string (like a dictionary key) to index a list, but lists only accept integers or slices for accessing their elements. This means somewhere in your parsed JSON data, a section you assumed was a dictionary is actually a list—or you're trying to pull a key directly from a list without first iterating through its items.
Example Scenario
Chances are your JSON structure looks something like this (super common with event-style data, like GitHub API responses):
[ { "type": "CreateEvent", "actor": { "login": "michael" } }, { "type": "PushEvent", "actor": { "login": "jane" } } ]
If you tried code like data["type"] here, it would throw the error immediately—because data is a list, not a dictionary.
The Fix
You need to iterate through the list first, check each dictionary entry for the "CreateEvent" type, then pull the nested "login" value. Here's a working example:
import json # Replace this with your actual JSON source (file, API response, etc.) json_raw = ''' [ { "type": "CreateEvent", "actor": { "login": "michael" } }, { "type": "PushEvent", "actor": { "login": "jane" } } ] ''' # Parse the JSON into a Python object parsed_data = json.loads(json_raw) # Loop through each event in the list for event in parsed_data: # Check if this is the event type we want if event.get("type") == "CreateEvent": # Grab the login value from the nested actor dictionary target_login = event["actor"]["login"] print(f"Found target login: {target_login}") # Outputs: michael
Pro Tips
- If you're unsure about your JSON structure, print it formatted to visualize layers clearly:
print(json.dumps(parsed_data, indent=2)) - If there are nested lists in your data, make sure to index them with integers first before accessing dictionary keys (e.g.,
event["some_nested_list"][0]["login"]).
内容的提问来源于stack exchange,提问作者j doe

