zoukankan      html  css  js  c++  java
  • 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)
    希望你眼眸有星辰,心中有山海,从此以梦为马,不负韶华
  • 相关阅读:
    应用量化时代 | 微服务架构的服务治理之路
    API网关——Kong实践分享
    容器云未来:Kubernetes、Istio 和 Knative
    微服务网关实战——Spring Cloud Gateway
    服务迁移之路 | Spring Cloud向Service Mesh转变
    基于事件驱动机制,在Service Mesh中进行消息传递的探讨
    MSMQ 和 MQTT
    MQTT和WebSocket
    NetCore WebSocket 即时通讯示例
    .NET 即时通信,WebSocket服务端实例
  • 原文地址:https://www.cnblogs.com/daviddd/p/12631168.html
Copyright © 2011-2022 走看看