Python Forum

Full Version: How to serialize custom class objects in JSON?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The Python documentation on JSON reads, "This simple serialization technique can handle lists and dictionaries, but serializing arbitrary class instances in JSON requires a bit of extra effort. The reference for the json module contains an explanation of this." But I can't seem to find the explanation in the JSON reference. I'm very new to programming, so it's probably there; it just went right over my head.

The reason I need to serialize the objects of a class I created is that I'm making a random NPC generator for tabletop RPGs, and each generated NPC is an instance of my NPC class with semi-randomized characteristics. Users will want to save the ones they like.

So how does one serialize a custom class object with JSON?

Thanks in advance.
google 'arbitrary class instance in JSON python'
In essence, it just boils down to making a JSON object where the keys are the field names (and so the values are, well, the field values). If you can make a dictionary in that form, you can just use json.dumps to produce a string containing the JSON representation.
(Sep-22-2019, 06:26 PM)ndc85430 Wrote: [ -> ]In essence, it just boils down to making a JSON object where the keys are the field names (and so the values are, well, the field values). If you can make a dictionary in that form, you can just use json.dumps to produce a string containing the JSON representation.

That's basically what I ended up doing, except I used a list instead of a dictionary:

def append_to_file(npc):
    """Append the attributes of an NPC to save file as a JSON string"""
    # Pull the attributes off an NPC class instance
    attrib_list = [npc.sex, npc.char, npc.principles, npc.law_disposition,
                   npc.trait1_type, npc.trait2_type, npc.trait1, npc.trait2,
                   npc.conf_ct1, npc.conf_ct2, npc.conf_tt, npc.quirk,
                   npc.prof_type, npc.prof, npc.con, npc.ill, npc.looks]
    # Open (or create) the save file in append mode
    with open("saved_npcs.txt", "a") as save_file:
        # Serializing attribute list to save file
        # as a JSON-formatted string
        save_file.write(json.dumps(attrib_list))
        save_file.write("\n")
Hello!
Look at jasonpickle module.