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

如何去除JSON文件中的反斜杠?Python实现遇阻求助

解决JSON输出多余反斜杠的问题

你的问题核心是做了两次JSON序列化:df1.to_json()已经把DataFrame转换成了合法的JSON字符串,结果你又用json.dump()把这个字符串再序列化一次,这就导致字符串里的双引号被自动转义,出现多余的\。

之前尝试的df.replace("\ "," ")和反斜杠问题无关,那是处理数据内的空格,根本没触及问题根源。

下面是两种直接有效的解决方法:

方法一:直接写入JSON字符串

跳过json.dump(),把to_json()生成的字符串直接写入文件:

import requests
import pandas as pd

headers = {
    'accept': 'application/json, text/plain, */*',
    'origin': 'https://www.nasdaq.com',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'
}

pd.set_option('display.max_columns', None)
pd.set_option('display.max_colwidth', None)

url = 'https://api.nasdaq.com/api/company/AAPL/institutional-holdings?limit=10&offset=0&type=TOTAL&sortColumn=marketValue&sortOrder=DESC'
r = requests.get(url, headers=headers)
df = pd.json_normalize(r.json()['data']['holdingsTransactions']['table']['rows'])
df1 = df.replace("\ "," ")
# 生成格式化的JSON字符串(加indent参数让输出更易读)
df_json_str = df1.to_json(indent=4)

with open('AAPL_institutional_table_MRKTVAL.json', 'w') as f:
    f.write(df_json_str)  # 直接写入字符串,无需二次序列化

方法二:用pandas直接写入文件(更简洁)

to_json()本身支持直接写入文件路径,省去手动处理文件的步骤:

import requests
import pandas as pd

headers = {
    'accept': 'application/json, text/plain, */*',
    'origin': 'https://www.nasdaq.com',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'
}

pd.set_option('display.max_columns', None)
pd.set_option('display.max_colwidth', None)

url = 'https://api.nasdaq.com/api/company/AAPL/institutional-holdings?limit=10&offset=0&type=TOTAL&sortColumn=marketValue&sortOrder=DESC'
r = requests.get(url, headers=headers)
df = pd.json_normalize(r.json()['data']['holdingsTransactions']['table']['rows'])
df.replace("\ "," ", inplace=True)
# 直接将DataFrame写入JSON文件,自动完成序列化
df.to_json('AAPL_institutional_table_MRKTVAL.json', indent=4)

内容的提问来源于stack exchange,提问作者kiestuthridge23

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 05:42:08