簡體   English   中英

將類對象列表保存到 JSON 文件中,以便以后讀取

[英]Saving a list of class objects to a JSON file that can be later read

TLDR - 我想將一些變量保存到 JSON 文件中。 其中一些是屬於自定義類的對象列表。 由於 JSON 無法序列化它們,因此會引發錯誤。 我怎樣才能做到這一點?

我正在做一個簡單的基於文本的頂級王牌程序,其中相關類如下:
播放器(以下子類)
人類
人工智能

卡片

我只編碼了大約 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 是 int
num_of_ai 是 int
總卡數是 int
卡片是卡片類的對象列表

我的目標是存儲所有這些變量的狀態,並能夠將它們相應地加載到頂部的變量中。 在當前狀態下,JSON 無法序列化我的自定義類的對象。

在 load_file() 中,我認為它實際上應該是:

total_cards = str(sf['total_cards'])

用這個改變你的load_file:

json.dump(data, f,default=lambda o:o.__dict__)

這應該可以解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM