简体   繁体   中英

JSON Serialization of Custom Objects (Encoding and Decoding)

I've been searching the internet and couldn't find a simple example to encode and decode a custom object using JSON in python.

Let's say I have the following class:

class Test:
    def __init__(self, name=None, grade=None):
        self.name = name
        self.grade = grade

and also have a list of Test objects:

t1 = Test("course1", 80)
t2 = Test("course2", 90)

list_of_tests = [t1, t2]

How can I serialize the class Test and the object list_of_tests using JSON? I want to be able to write it to a file and read it from a file, using python.

You can control how an unrecognised object is serialised by dumps(default=converter_function). For it to be valid JSON you'd have to return a plain dict with the fields you want plus some tag field identifying that it is to be treated specially by loads.

Then have another converter function to reverse the process passed to loads() as object_hook.

To be honest the easiest thing to do here is to manually create a list of dictionaries from your objects. Then you can pass that directly to the JSON functions.

data = [{'name': x.name, 'grade': x.grade} for x in list_of_tests]
with open('output.json', 'w') as out:
    json.dump(data, out)

and read it back:

with open('output.json') as inp:
    data = json.load(inp)
    list_of_tests = [Test(x['name'], x['grade']) for x in data]

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