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

Viewed 443

TLDR - I want to save a few variables to a JSON file. Some of these are lists of objects belonging to custom classes. An error is raised as JSON cannot serialize them. How can I do this?

I am doing a simple text-based top trumps program where the relevant classes are as follows:
Player (sub-classes below)
Human
AI

Card

I've only been coding for around 3 months. My code for the project itself is completely functional, but I'm implementing a load option on the opening and a save option at the end of each round.

Below is my config module, it contains all the variables that are accessed by other modules, and contains everything that'd be needed for a save/load.

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'])

Description of these variables:
total_players is the total amount of players as an integer
players is a list of objects that belong to either the Human or Ai class
dead_players is same as above
(self explanatory below)
num_of_humans is int
num_of_ai is int
total cards is int
cards is a list of objects of class Card

My aim is to store the state of all of these variables and be able to load them accordingly to the variables at the top. In it's current state, JSON cannot serialize the objects of my custom classes.

2 Answers

In load_file(), I think it should actually be:

total_cards = str(sf['total_cards'])

change your load_file with this:

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

This should solve your problem.

Related