调用Upbit API提取标题时触发KeyError: 'title'问题求助
Let's break down why you're hitting this KeyError: 'title' and walk through how to fix it, step by step.
1. Diagnose the Root Cause
The error means the path before['data']['title'] doesn't exist in your data—either the Upbit API has changed its response structure, or your local notice.json file contains malformed/old data that doesn't match your expected schema.
First, let's confirm what the API actually returns. Add this quick debug snippet to your code:
import requests # Fetch and print the raw API response response = requests.get('https://manager.upbit.com/api/v1/') print("API Response:", response.json()) print("Status Code:", response.status_code)
Run this, and check the output. Common issues here include:
datais a list instead of a dictionary (so you'd needdata[0]['title']instead)- The key name changed (e.g.,
subjectinstead oftitle) - The API returns an error object (no
datakey at all)
2. Fix Key Access with Safe Checks
Never directly index dictionary keys without verifying they exist—this is the #1 cause of KeyError in Python. Use these safer approaches:
Option 1: Use dict.get() for graceful fallback
The get() method returns a default value (like None) if the key doesn't exist:
# Replace before['data']['title'] with this before_set = before.get('data', {}).get('title') if not before_set: print("Warning: Title not found in response. API structure may have changed.")
Option 2: Explicitly check for key existence
For more control, verify each key exists before accessing it:
if 'data' in before and 'title' in before['data']: before_set = before['data']['title'] else: before_set = None print("Missing 'data' or 'title' key—check API response structure.")
3. Updated Robust Code
Here's your full code with error handling, safe key access, and protection against corrupted local files:
import requests import json def fetch_and_check_notice(): # Load existing notice from file (if possible) before = {} try: with open('notice.json', 'r') as current_notice: before = json.loads(current_notice.read()) except (IOError, json.JSONDecodeError): # File missing or corrupted—fetch fresh data from API print("Local notice file not found/corrupted. Fetching from API...") response = requests.get('https://manager.upbit.com/api/v1/') if response.status_code == 200: before = response.json() # Save fresh data to file with open('notice.json', 'w') as f: json.dump(before, f, indent=2) else: print(f"API request failed with status code: {response.status_code}") return None # Safely extract title current_title = before.get('data', {}).get('title') return current_title # Test the function title = fetch_and_check_notice() if title: print(f"Current notice title: {title}") else: print("Failed to retrieve notice title. Verify API response structure.")
4. Additional Checks to Rule Out Edge Cases
- API Region/Rate Limits: If you're getting a non-200 status code, check if your IP is restricted or if you've hit rate limits.
- Array vs. Dict: If
datais a list (e.g.,[{"title": "..."}]), adjust the code to accessbefore['data'][0]['title'](and add a check to ensure the list isn't empty).
内容的提问来源于stack exchange,提问作者ssithuxx

