KeyError #817
-
Hi everyone! I’m trying to write a Python script that fetches JSON data from an API and prints the value of a specific key. But I keep running into a KeyError. Here’s my code: response = requests.get("https://api.example.com/data") print(data["results"]["name"]) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Great question! The KeyError happens because the JSON structure is not exactly what you’re expecting. Sometimes APIs wrap data differently (e.g., in a list, or under another key). To debug, try printing the full JSON response first: |
Beta Was this translation helpful? Give feedback.
Great question! The KeyError happens because the JSON structure is not exactly what you’re expecting. Sometimes APIs wrap data differently (e.g., in a list, or under another key).
To debug, try printing the full JSON response first:
print(data)
If results is actually a list, you’d need to access it like this:
print(data["results"][0]["name"])
Or if the data doesn’t contain results at all, you may need to check which keys are present:
print(data.keys())
As a best practice, you can also use .get() to avoid errors when a key is missing:
print(data.get("results", {}).get("name", "Key not found"))
This way, your script won’t crash if the API response changes unexpectedly.