Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

python - 如何使可序列化的JSON类(How to make a class JSON serializable)

How to make a Python class serializable?

(如何使Python类可序列化?)

A simple class:

(一个简单的类:)

class FileItem:
    def __init__(self, fname):
        self.fname = fname

What should I do to be able to get output of:

(我应该怎么做才能获得输出:)

>>> import json

>>> my_file = FileItem('/foo/bar')
>>> json.dumps(my_file)
TypeError: Object of type 'FileItem' is not JSON serializable

Without the error

(没有错误)

  ask by Sergey translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is a simple solution for a simple feature:

(这是一个简单功能的简单解决方案:)

.toJSON() Method (.toJSON()方法)

Instead of a JSON serializable class, implement a serializer method:

(代替JSON可序列化的类,实现一个序列化器方法:)

import json

class Object:
    def toJSON(self):
        return json.dumps(self, default=lambda o: o.__dict__, 
            sort_keys=True, indent=4)

So you just call it to serialize:

(因此,您只需调用它即可序列化:)

me = Object()
me.name = "Onur"
me.age = 35
me.dog = Object()
me.dog.name = "Apollo"

print(me.toJSON())

will output:

(将输出:)

{
    "age": 35,
    "dog": {
        "name": "Apollo"
    },
    "name": "Onur"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...