Sep-22-2019, 06:53 PM
(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")