Search code examples
pythonjsonserialization

Serialize/Deserialize list of objects using json and python


How do i serialize a list of objects(Person) to a json file and then read that json file back and deserialize them back into objects? I know how to write to a json file but i'm not clear on how to convert my objects to json properly.

Below is my simplified snippet of code. I have a list containing two people and i want to serialize them and save to a json file. Then deserialize them back to objects of type People.

Thanks for the help.

import json

class Person(object):
    def __init__(self, name, nickname):
        self.name = name
        self.age = 0
        self.nickname = nickname

# create a few people
A = Person('John', 'Joker')
B = Person('Marisa', 'Snickerdoodle')

# add people to list
peeps = []
peeps.append(A)
peeps.append(B)

# dummy data saving to json for testing
data = {
   'name' : 'ACME',
   'shares' : 100,
   'price' : 542.23
}

with open('data.json', 'w') as outfile:
    json.dump(data, outfile)

Solution

  • The json module expects lists, dicts, strings, numbers, booleans, and None, not custom classes. You need to make a dictionary out of your People instance. A simple way to do this is with vars(A).