python解决json序列化时间格式 --json

json

import json
from datetime import datetime
from datetime import date

info = {
	"name": "ffm",
	"birth": datetime.now(),
	"age": 18,
	'hobbies': ['music', 'read', 'dancing'],
	'addr': {
		'country': 'China',
		'city': 'shanghai'
	}
}


class CJsonEncoder(json.JSONEncoder):

	def default(self, obj):
		if isinstance(obj, datetime):
			return obj.strftime('%Y-%m-%d %H:%M:%S')
		elif isinstance(obj, date):
			return obj.strftime('%Y-%m-%d')
		else:
			return json.JSONEncoder.default(self, obj)


json_info = json.dumps(info, cls=CJsonEncoder)
print(json_info)

。。。

"""
json_info = {
	"name": "ffm",
	"birth": "2020-04-04 11:51:40",
	"age": 18,
	"hobbies": [
			"music",
			"read",
			"dancing"
			],
	"addr": {
		"country": "China",
		"city": "shanghai"
	}
}

"""

进一步的进阶使用,将MongoDB和sqlalchemy加入

from datetime import date, datetime
# MongoDB的id
from bson import ObjectId
import json
# sqlalchemy的元类
from sqlalchemy.ext.declarative import DeclarativeMeta


class JSONEncoder(json.JSONEncoder):
	def default(self, obj):
		if isinstance(obj, datetime):
			return obj.strftime('%Y/%m/%d %H:%M:%S')
		elif isinstance(obj, date):
			return obj.strftime('%Y-%m-%d')
		# 如果是MongoDB的id,将其转成字符串
		elif isinstance(obj, ObjectId):
			return str(obj)
		elif isinstance(obj, bytes):
			return obj.decode()
		# 如果是sqlalchemy数据库对象将其拆分,拼接成字典
		elif isinstance(obj.__class__, DeclarativeMeta):
			res = {}
			for key in obj.__dict__:
				if key[0] != "_":
					res[key] = obj.__dict__[key]
			return res
		else:
			return json.JSONEncoder.default(self, obj)
posted @ 2020-04-04 12:02  阿浪阿浪  阅读(805)  评论(0编辑  收藏  举报