开发网站,离不了Json
但是一般情况,不支持python的其它对象,怎么办?
有办法:Json 序列化!!!
总体来说,需要序列化的数据类型为 字典,类,嵌套类.
下面是我做的一个demo,都包含了:
import json
from flask import Flask
app=Flask(__name__)
class Info():
def __init__(self,state,time,user):
self.state=state
self.time=time
self.user=user
class Admin():
def __init__(self,state,time,user,year,country):
self.year=year
self.country=country
self.info=Info(state,time,user)
@app.route('/class_json/')
def on():
info=Info('class','2018-07-24-04-22','huhai')
info_to_dict=info.__dict__
info_to_json=json.dumps(obj=info_to_dict)
return info_to_json
@app.route('/complex-class_json/')
def on_():
admin=Admin('complex-class_json','2018-07-24-04-52','huhai','2018','china')
admin_to_json=json.dumps(admin,default=lambda obj:obj.__dict__,sort_keys=True,indent=4)
return admin_to_json
@app.route('/dict_json/')
def dict_to_json():
dict_obj={}
dict_obj['state']='dict data'
dict_obj['time']='2018-07-24-04-02'
dict_obj['user']='hu hai'
json_obj=json.dumps(dict_obj)
return json_obj
if __name__=='__main__':
app.run(debug=True)