对齐打印对象属性python
print 输出对象 dict 全挤在一行,很难看。所以但愿输出相似 json 对齐的方式。json
基本的思想是转成 json 格式再输出。随便一搜,找到以下代码,普通状况下可用:code
def obj_to_json():
stu = Student(28, 'male', '13000000000', '123@qq.com')
print(type(stu)) #
print(stu)
stu = stu.__dict__ # 将对象转成dict字典
print(type(stu)) #
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"
}字符串