Python request.json()方法单引号转’的原因及解决方法求助
r.json() Let’s break down why this is happening and how to fix it:
Common Causes
1. The Server Is Sending Curly Quotes Already
This is the most likely scenario. Many websites or APIs automatically replace straight single quotes (') with curly apostrophes (’) for typographical consistency before sending responses. When you call r.json(), you’re just receiving the data exactly as the server provided it—no conversion is happening during the JSON parsing step itself.
2. Accidental Conversion in Your Code
Double-check if there’s any intermediate step between receiving the response and calling r.json() that might be altering the text. For example:
- Using a text-processing library (like typography tools or markdown parsers) that converts "dumb" quotes to "smart" quotes.
- Manually modifying
r.textbefore passing it to a JSON parser (instead of using the built-inr.json()method).
How to Fix It
If the Server Is Sending Curly Quotes
You’ll need to convert the curly apostrophes back to straight quotes after parsing the JSON. Here’s a recursive approach (in Python) that handles strings, lists, and dictionaries:
import requests response = requests.get("your-api-url") data = response.json() def restore_straight_quotes(obj): if isinstance(obj, str): # Replace curly apostrophe with straight single quote return obj.replace("’", "'") elif isinstance(obj, list): return [restore_straight_quotes(item) for item in obj] elif isinstance(obj, dict): return {key: restore_straight_quotes(value) for key, value in obj.items()} # Leave other types (numbers, booleans, null) unchanged return obj fixed_data = restore_straight_quotes(data)
If Your Code Is Causing the Conversion
- Remove any text-processing steps that might be altering quotes before you parse the JSON. Stick directly to
response.json()to get the raw parsed data. - If you’re manually parsing
response.text, ensure you’re not using any libraries or functions that perform smart quote conversion on the text.
内容的提问来源于stack exchange,提问作者Konstantin Yakushenko

