简体   繁体   中英

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)

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) .

You cannot serialize custom classes using JSON.

You should use the pickle module instead. From the docs:

https://docs.python.org/3/library/pickle.html#comparison-with-json

JSON, by default, can only represent a subset of the Python built-in types, and no custom classes ;

Emphasis mine.

Also, from http://www.json.org/ :

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary , hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list , or sequence.

Again, emphasis is mine. In python, you can serialize dictionaries or lists that contain values, where values can be:

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

add to_dict method to your person class. try this

In [2]: class Person(object):
   ...:         def __init__(self, name, nickname):
   ...:                 self.name = name
   ...:                 self.age = 0
   ...:                 self.nickname = nickname
   ...:         def to_dict(self):
   ...:             data = {}
   ...:             data['name'] = self.name
   ...:             data['age'] = self.age
   ...:             return data
   ...:         
peeps = []
peeps.append(A.to_dict())
peeps.append(B.to_dict())

In [9]: with open('data.json', 'w') as outfile:
   ...:     json.dump(peeps, outfile)

In [10]: !cat data.json
[{"age": 0, "name": "John"}, {"age": 0, "name": "Marisa"}]

Update: To deserialize json to python object

In [4]: with open('data.json', 'r') as infile:
   ....     data = json.loads(infile.read())
   ...:     
In [5]: A = Person(data[0]['name'], data[0]['nickname'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM