本篇文章給大家帶來的内容是關于Python自定義類對象序列化為Json串(代碼示例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。
之前已經實作了Python: Json串反序列化為自定義類對象,這次來實作了Json的序列化。
測試代碼和結果如下: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按Enter鍵退出。")
運作結果:kid100The Little Prince
{"books": [{"name": "math", "type": "study"}, {"name": "The Little Prince", "type": "literature"}], "id": "123", "name": "kid", "score": {"chinese": 98, "math": 100}}
按Enter鍵退出。
實作代碼如下: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)) == "":
# value 為清單
for index in range(0, value.__len__()):
value[index] = value2py_data(value[index])
return value