JSON格式错误求助:单引号引发解析失败及requests库字典转换问题
Hey Johnny, I’ve run into this exact headache before—JSON’s strict rules can clash hard with Python’s flexible dict syntax. Let’s break down why this is happening and the easiest fixes to get your requests working:
Why You’re Seeing This Error
JSON has non-negotiable rules that Python dicts don’t enforce:
- All property names must be wrapped in double quotes (
") - String values also require double quotes (even though Python lets you use single quotes for dict strings)
Your single-quoted string isn’t valid JSON, so the parser that requests uses under the hood throws that error. Adding double quotes just around the whole string doesn’t fix the internal single quotes on property names, which is why that quick fix didn’t work.
The Best Solutions
1. Skip the JSON String Entirely (Recommended)
Requests accepts Python dicts directly via the json parameter—you don’t need to convert to a JSON string yourself! It will automatically serialize the dict into valid, double-quoted JSON for you.
Example:
import requests # Your original structure as a native Python dict (single quotes are fine here) headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer your-token'} payload = {'user_id': 123, 'action': 'update'} # Pass the dict directly to the `json` parameter response = requests.post('https://your-api-endpoint.com', json=payload, headers=headers)
2. Parse Single-Quoted Strings with ast.literal_eval()
If you have to work with a single-quoted string (e.g., it’s coming from an external source), use Python’s ast.literal_eval() instead of json.loads(). This function safely parses Python-like structures (including single-quoted dicts) into actual Python objects without breaking valid string content.
Example:
import ast import requests # Your single-quoted string input single_quoted_str = "{'name': 'Alice', 'email': 'alice@example.com'}" # Convert to a valid Python dict valid_dict = ast.literal_eval(single_quoted_str) # Now use it with requests response = requests.post('https://your-api-endpoint.com', json=valid_dict)
3. Manually Fix the JSON String (Not Recommended)
If you really need to convert the string to valid JSON, you’d have to replace all property name single quotes with double quotes, and escape any single quotes inside string values. This is error-prone (it breaks if your string values have unescaped single quotes), but here’s a basic example:
import json import requests single_quoted_str = "{'product': 'Laptop', 'description': '15-inch model'}" # Replace property name single quotes with double quotes valid_json_str = single_quoted_str.replace("'", '"') # Parse into a dict valid_dict = json.loads(valid_json_str)
Stick with the first two methods—they’re way more reliable and save you from messy string manipulation!
内容的提问来源于stack exchange,提问作者Johhny

