【问题标题】:Saving a list of class objects to a JSON file that can be later read将类对象列表保存到 JSON 文件中,以便以后读取
【发布时间】:2021-11-14 01:03:47
【问题描述】:

TLDR - 我想将一些变量保存到 JSON 文件中。其中一些是属于自定义类的对象列表。由于 JSON 无法序列化它们,因此会引发错误。我该怎么做?

我正在做一个简单的基于文本的顶级王牌程序,其中相关类如下:
Player(以下子类)
人类
人工智能

卡片

我只编写了大约 3 个月的代码。我的项目代码本身是完全正常的,但我在开始时实现了一个加载选项,在每一轮结束时实现了一个保存选项。

下面是我的配置模块,它包含其他模块访问的所有变量,并包含保存/加载所需的所有内容。

import json

#All variables that need to be accessed between various modules publicly
total_players = 0
players = []
dead_players = []
num_of_humans = 0
num_of_ai = 0
total_cards = 0
cards = []

def save_file():
    save_name = input("Save name (You will use this to load) > ")
    path = 'path_to_dir{0}.json'.format(save_name)
    data = {
        'total_players' : total_players,
        'players' : players,
        'dead_players' : dead_players,
        'num_of_humans' : num_of_humans,
        'num_of_ai' : num_of_ai,
        'total_cards' : total_cards,
        'cards' : cards
    }
    with open(path, 'w+') as f:
        json.dump(data, f)

def load_file():
    load_name = input(f"Enter the name of your save > ")
    path_two = 'path_to_dir{0}.json'.format(load_name)
    with open(path_two, 'r') as f: 
        sf = json.load(f) 
        total_players = str(sf['total_players'])
        players = str(sf['players'])
        dead_players = str(sf['dead_players'])
        num_of_humans = str(sf['num_of_humans'])
        num_of_ai = str(sf['num_of_ai'])
        total_cards = str(sf['total_card'])
        cards = str(sf['cards'])

这些变量的说明:
total_players 是整数形式的玩家总数
玩家是属于 Human 或 Ai 类的对象列表
dead_players 同上
(下面自解释)
num_of_humans 是整数
num_of_ai 是 int
总卡数是 int
Cards 是 Card 类的对象列表

我的目标是存储所有这些变量的状态,并能够将它们相应地加载到顶部的变量中。在当前状态下,JSON 无法序列化我的自定义类的对象。

【问题讨论】:

    标签: python json class save


    【解决方案1】:

    在load_file()中,我觉得其实应该是:

    total_cards = str(sf['total_cards'])
    

    【讨论】:

    • 如果这修复了代码,您能否将我的回复标记为已接受?谢谢!
    • 嗨,虽然它确实解决了加载中的一个问题(谢谢),但它实际上并没有解决手头的问题。我将在顶部重复 TLDR:我想将一些变量保存到 JSON 文件中。其中一些是属于自定义类的对象列表。由于 JSON 无法序列化它们,因此会引发错误。我该怎么做?
    • @custord 我们无法帮助您,除非您向我们展示您的类是如何定义的,或者至少是它们外观的缩写模式。我建议还研究一下 Python dataclasses,因为它有一个辅助函数 asdict,可用于将数据类实例(包括嵌套的数据类对象)序列化为 dict/JSON 对象。
    猜你喜欢
    • 2014-06-03
    • 2019-12-21
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多