Python Flask中JSON访问报错:TypeError: string indices must be integers
Fixing the TypeError: string indices must be integers in your Python API code
Hey there! Let's break down what's causing that error and fix it quickly.
The Root Cause
Your issue comes from a common mix-up between parsed Python objects and JSON strings:
- When you run
json.loads(connection.getresponse().read().decode('utf-8')), you're converting the API's JSON response into a Python dictionary (stored inresponse). This is exactly what you want, since dictionaries let you access values with keys like["matchday"]. - But then you do
json = json.dumps(response)— this takes that dictionary and converts it back into a JSON-formatted string. Nowjsonis no longer a dictionary, it's a string, and strings only accept integer indices (likemy_string[0]), hence theTypeError.
The Fix
Just remove the line that converts the dictionary back to a string, and directly access the value from the parsed response dictionary. Here's your corrected code:
def search_team(): import http.client import json connection = http.client.HTTPConnection('api.football-data.org') headers = { 'X-Auth-Token': 'c4c0ba9c685041aca2fase3d1b2fa5e585', 'X-Response-Control': 'minified' } connection.request('GET', '/v1/competitions/445/leagueTable', None, headers ) # Parse the JSON response into a Python dictionary response = json.loads(connection.getresponse().read().decode('utf-8')) # Directly return the matchday value from the dictionary return response["matchday"] if __name__ == '__main__': app.run()
Extra Note
If you need to return a properly formatted JSON response (for example, in a Flask app), instead of returning the raw integer, you can use Flask's jsonify function:
from flask import jsonify # ... inside search_team ... return jsonify({"matchday": response["matchday"]})
This ensures the response is structured correctly for any clients consuming your endpoint.
内容的提问来源于stack exchange,提问作者You Awesum




