對齊打印對象屬性python
print 輸出對象 dict 全擠在一行,很難看。所以但願輸出相似 json 對齊的方式。json
基本的思想是轉成 json 格式再輸出。隨便一搜,找到以下代碼,普通狀況下可用:code
def obj_to_json(): stu = Student(28, 'male', '13000000000', '123@qq.com') print(type(stu)) # <class 'json_test.student.Student'> print(stu) stu = stu.__dict__ # 將對象轉成dict字典 print(type(stu)) # <class 'dict'> print(stu) j = json.dumps(obj=stu, indent=4) print(j)
但有些對象中會包含一些特殊屬性,如另一個對象,則用此法會報錯:對象
TypeError: Object of type xxx is not JSON serializable
其實就是 JSON 不支持這種對象。咱們能夠自定義處理特殊對象的方法,完整代碼以下:utf-8
# encoding:utf-8 # author: over import json from datetime import datetime, date class Student(object): def __init__(self, age, sex, mobile, date): self.age = age self.sex = sex self.mobile = mobile self.date = date # 擴展 json 沒法解析的類型 class ComplexEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): # return obj.strftime('%Y-%m-%d %H:%M:%S') return str(obj) elif isinstance(obj, date): # return obj.strftime('%Y-%m-%d') return str(obj) else: try: return json.JSONEncoder.default(self, obj) except Exception as e: print('type not support: '+str(obj)) # 默認的處理不了直接強轉字符串 return str(obj) # json 對齊方式輸出對象全部屬性,方便查看 def printJson(obj): if hasattr(obj,'__dict__'): obj = obj.__dict__ # ensure_ascii=False 中文不變成百分符 # indent 縮進行增長的空格數 j = json.dumps(obj, cls=ComplexEncoder, ensure_ascii=False, indent=4) print(j) if __name__ == '__main__': stu = Student(28, 'male', '13000000000', datetime.now()) printJson(stu)
輸出:ci
{
"age": 28,
"sex": "male",
"mobile": "13000000000",
"date": "2019-07-07 14:43:51.466416"
}字符串