You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python request.json()方法单引号转’的原因及解决方法求助

Why Your Single Quotes Are Turning to Curly Apostrophes After 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.text before passing it to a JSON parser (instead of using the built-in r.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:20:06