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

如何解决Python字符串转JSON时外层引号无法去除的问题?

解决Python中json.dump()写入数组时带外层引号的问题

问题描述

你通过手动拼接字符串生成了类似JSON数组的内容,用json.dump()写入文件后,结果始终带有外层引号,变成了一个字符串而非合法的JSON数组。尝试用str.strip('""')去除引号也无效。

当前输出:

"[{'number1':1, 'number2': 2, 'number3': 3, 'word1': 'word'},{'number1':2, 'number2': 2, 'number3': 3, 'word1': 'word'}]"

期望输出:

[{"number1":1, "number2": 2, "number3": 3, "word1": "word"},{"number1":2, "number2": 2, "number3": 3, "word1": "word"}]

问题根源

你的batchStr函数是手动拼接字符串,返回的结果是Python的字符串类型。当你把这个字符串传给json.dump()时,JSON库会将其视为普通字符串处理,自动在外层添加引号并转义内部特殊字符,最终写入的自然是带引号的字符串,而非JSON数组。

解决方案:直接操作Python原生数据结构

不要手动拼接JSON格式的字符串,直接使用Python的列表和字典来构建数据,让json模块自动完成序列化,这是最可靠的方式。

修改后的代码

替换原来的batchStr函数:

def batch_data(batchIds, count1, count2, status):
    result = []
    for idx in range(len(batchIds)):
        item = {
            'batchId': batchIds[idx],
            'source1count': count1[idx],
            'source2count': count2[idx],
            'status': status[idx]
        }
        result.append(item)
    return result

使用示例

调用函数得到原生数据结构后,直接传给json.dump():

import json

# 测试数据示例
batch_ids = [1, 2]
counts1 = [10, 20]
counts2 = [5, 15]
statuses = ["success", "pending"]

# 生成Python列表
data = batch_data(batch_ids, counts1, counts2, statuses)

# 写入JSON文件
with open('output.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, indent=2)

这样写入的文件会是标准的JSON数组,没有外层引号,且自动将单引号转为JSON规范要求的双引号。

备选方案:处理已拼接的字符串(不推荐)

如果已经有了手动拼接好的字符串,可先将其转为Python对象再写入,但这种方式容易因格式错误出问题:

import json

# 假设str1是原函数返回的字符串
str1 = "[{'batchId':1, 'source1count': 10, ...}, ...]"
# 先将单引号替换为双引号(符合JSON规范)
fixed_str = str1.replace("'", '"')
# 解析为Python列表
data = json.loads(fixed_str)

# 写入文件
with open('output.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, indent=2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 12:40:21