使用Python(Flask)调用Qwant API遇JSON解码错误求解决方案
Hey there! Let's break down why you're running into that simplejson.errors.JSONDecodeError and how to fix it.
The Core Issue: Malformed API URL
Your URL contains & instead of plain & characters. Those & are HTML entities used to represent ampersands in web pages, but when you send them directly in an API request, the Qwant server doesn't interpret them as parameter separators. This means your request is invalid, and instead of getting back the JSON data you expect, you're probably receiving an HTML error page—hence the "Expecting value" decode error.
Fixed Code with Key Improvements
Here's the corrected version of your code, with extra tweaks to avoid common pitfalls:
import requests from flask import Flask, jsonify # Don't forget to initialize your Flask application! app = Flask(__name__) @app.route("/display") def display(): # Replace & with & in the API URL api_url = "https://api.qwant.com/api/search/images?count=10&offset=1&q=stackoverflow" # Add a proper User-Agent header—many public APIs block requests without one request_headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" } try: # Send the request with headers response = requests.get(api_url, headers=request_headers) # Raise an error if the request returns an HTTP status code like 404 or 500 response.raise_for_status() # Parse the JSON response image_data = response.json() # Use Flask's jsonify to return properly formatted JSON return jsonify(image_data) # Catch and handle any request-related errors except requests.exceptions.RequestException as e: return jsonify({"error": f"Request failed: {str(e)}"}), 500
What Changed & Why?
- Fixed URL: Replaced
&with&to ensure parameters are correctly separated for the API. - Initialized Flask App: Added
app = Flask(__name__)—your original code was missing this critical line, which would have caused another error once the URL issue was fixed. - Added User-Agent Header: Public APIs often block requests with default
requestslibrary headers (which look like bots). Adding a browser-like User-Agent helps avoid being blocked. - Used
jsonify: Flask'sjsonifyfunction sets the correctContent-Typeheader for JSON responses, which is better practice than returning raw JSON data directly. - Error Handling: Wrapped the request in a
try/exceptblock to catch HTTP errors, network issues, or JSON parsing failures, making it easier to debug problems.
Give this code a try—it should resolve the JSON decode error and return the image data you're looking for!
内容的提问来源于stack exchange,提问作者Rienk

