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

求助:Python写入JSON文件时数据格式异常问题

问题原因及解决方法

你代码的问题在于重复序列化:

  • json.dumps(person, ...)已经把Python字典转换成了标准的JSON格式字符串
  • 后续调用json.dump(personJSON, file)时,会把这个字符串当作普通Python字符串再次序列化,导致输出内容带上了转义字符和外层引号。

两种修复方案

方案一:直接序列化字典到文件(推荐)

跳过dumps()步骤,直接用json.dump()把Python字典写入文件,同时传入格式化参数:

import json

person = {
    "Name": "William", 
    "Age": 30,
    "full-time": True
}

with open('person.json', 'w') as file:
    json.dump(person, file, indent=4, sort_keys=True)

方案二:写入已序列化的JSON字符串

如果已经通过dumps()得到了JSON字符串,直接用文件对象的write()方法写入,不要用json.dump():

import json

person = {
    "Name": "William", 
    "Age": 30,
    "full-time": True
}

personJSON = json.dumps(person, indent=4, sort_keys=True)

with open('person.json', 'w') as file:
    file.write(personJSON)

执行任意一种方案后,person.json里都会得到正确的JSON内容:

{
    "Age": 30,
    "Name": "William",
    "full-time": true
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:27:19