Home > Backend Development > Python Tutorial > Python custom class object serialized into Json string (code example)

Python custom class object serialized into Json string (code example)

不言
Release: 2019-03-06 17:28:08
forward
3399 people have browsed it

The content of this article is about serializing Python custom class objects into Json strings (code examples). It has certain reference value. Friends in need can refer to it. I hope It will help you.

I have implemented Python before: deserializing Json strings into custom class objects. This time I will implement Json serialization.

The test code and results are as follows:

import Json.JsonTool
class Score:
    math = 0
    chinese = 0
class Book:
    name = ''
    type = ''
class Student:
    id = ''
    name = ''
    score = Score()
    books = [Book()]
student = Student()
json_data = '{"id":"123", "name":"kid", "score":{"math":100, "chinese":98}, ' \
            '"books":[{"name":"math", "type":"study"}, ' \
            '{"name":"The Little Prince", "type":"literature"}]} '
Json.JsonTool.json_deserialize(json_data, student)
print(student.name)
print(student.score.math)
print(student.books[1].name)
student_str = Json.JsonTool.json_serialize(student)
print(student_str)
input("\n按回车键退出。")
Copy after login

Running results:

kid100The Little Prince
{"books": [{"name": "math", "type": "study"}, {"name": "The Little Prince", "type": "literature"}], "id": "123", "name": "kid", "score": {"chinese": 98, "math": 100}}

按回车键退出。
Copy after login

The implementation code is as follows:

def json_serialize(obj):
    obj_dic = class2dic(obj)
    return json.dumps(obj_dic)


def class2dic(obj):
    obj_dic = obj.__dict__
    for key in obj_dic.keys():
        value = obj_dic[key]
        obj_dic[key] = value2py_data(value)
    return obj_dic


def value2py_data(value):
    if str(type(value)).__contains__('__main__'):
        # value 为自定义类
        value = class2dic(value)
    elif str(type(value)) == "<class &#39;list&#39;>":
        # value 为列表
        for index in range(0, value.__len__()):
            value[index] = value2py_data(value[index])
    return value
Copy after login

The above is the detailed content of Python custom class object serialized into Json string (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template