zoukankan      html  css  js  c++  java
  • python解决json序列化时间格式

    简单实例

    import json
    from datetime import datetime
    from datetime import date
    
    info = {
        "name": "ffm",
        "birth": datetime.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)
    #进一步的进阶使用,将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)
  • 相关阅读:
    nginx增加lua支持
    使用nginx+lua实现web项目的灰度发布
    amoeba学习
    信号有关的内容
    Linux系统的进程相关内容
    等待类型
    孤立用户故障排除
    恢复数据库
    执行计划之Insert,update,delete
    临时表和表变量
  • 原文地址:https://www.cnblogs.com/angelyan/p/10518856.html
Copyright © 2011-2022 走看看