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

Python向JSON文件追加字典生成无效格式,如何合并为单字典?

问题原因与解决方法

你之前的错误在于直接将单个字典追加写入JSON文件,这会导致文件里是多个独立的JSON对象拼接(比如{"john":5}{"ana":7}),而JSON语法要求整个文件必须是一个合法的单一结构(比如一个大字典或数组)。

正确的做法是每次操作都先读取文件中已有的完整数据,合并新成绩后再覆盖写入文件,步骤如下:

具体实现代码

import json
import os

def save_highscore(username, attempts):
    highscore_file = "highscores.json"
    
    # 读取已有成绩:文件不存在则初始化空字典
    if os.path.exists(highscore_file):
        with open(highscore_file, "r", encoding="utf-8") as f:
            highscores = json.load(f)
    else:
        highscores = {}
    
    # 更新成绩:如果用户未记录,或新尝试次数更少(最佳成绩),则更新
    if username not in highscores or attempts < highscores[username]:
        highscores[username] = attempts
    
    # 将完整的字典写入文件(覆盖原有内容)
    with open(highscore_file, "w", encoding="utf-8") as f:
        json.dump(highscores, f, indent=4, ensure_ascii=False)

关键说明

  1. 不要用追加模式("a")写入JSON:追加会破坏JSON的整体结构,导致文件无法被json.load()正常解析。
  2. 先读再写:每次保存前先加载已有数据,合并新记录后再完整写入,保证文件始终是一个合法的JSON字典。
  3. 灵活调整存储结构:如果需要保留用户的所有历史记录而非仅最佳成绩,可以把存储结构改成列表(比如[{"username": "john", "attempts":5}, {"username": "ana", "attempts":7}]),读取后用append添加新记录再写入即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:20:27