Python Forum
How to serialize custom class objects in JSON? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to serialize custom class objects in JSON? (/thread-21226.html)



How to serialize custom class objects in JSON? - Exsul1 - Sep-19-2019

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.


RE: How to serialize custom class objects in JSON? - Larz60+ - Sep-20-2019

google 'arbitrary class instance in JSON python'


RE: How to serialize custom class objects in JSON? - ndc85430 - Sep-22-2019

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.


RE: How to serialize custom class objects in JSON? - Exsul1 - Sep-22-2019

(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")



RE: How to serialize custom class objects in JSON? - wavic - Sep-23-2019

Hello!
Look at jasonpickle module.