Python将普通Class对象转为Json字符串

import json


class Test:
    """
    age
    name
    """

    # init args :age、sname
    age = 0
    name = ''


def obj_json():
    """
    convert object to json str
    :return json str:
    """
    test = Test()
    test.age = 20
    test.name = 'kitty'
    list_test = []
    list_test.append(test)
    test = Test()
    test.age = 30
    test.name = 'hello'
    list_test.append(test)
    json_str = json.dumps(list_test, default=lambda o: o.__dict__)
    print(json_str)
    return json_str


res = obj_json()
print('object convert json:' + res)

  

posted @ 2022-10-13 21:00  lucky_tomato  阅读(831)  评论(0编辑  收藏  举报