zoukankan      html  css  js  c++  java
  • json的拓展应用

    from datetime import datetime,date
    import json
    # json.JSONEncoder
    res1 = datetime.today()
    
    res2 = date.today()
    
    dict = {'1':res1,'2':res2} # Object of type 'datetime' is not JSON serializable 报错
    
    """
    Object of type 'datetime' is not JSON serializable
    可以知道res1所代表的datetime.today()的数据类型 是json所不能序列化的 那么我们序列化的时候是按照什么标准来的呢 可以知道之前讲过
    JSONEncoder 里面有能够序列化的数据类型,那么当我们进入dump时 可以发现有一个cls的形参默认值为None,那么当这个形参为None时,会
    自动使用JSONEncoder类 的序列化方式 ,因此我们想要修改其中数据类型的普适性,那么我们需要重新创建一个类,通过默认值default方法将
    其返回为字符串数据,所以就要将datetime.today()的结构化时间转化为 字符串的格式化时间 strftime()
    """ class OwnJSON(json.JSONEncoder): def default(self, o): if isinstance(o,datetime): return o.strftime('%Y-%m-%d %X') elif isinstance(o,date): return o.strftime('%Y-%m-%d') else: return super().default(self,o) # 上述条件都不属于 那么就返回父类的方法 print(json.dumps(dict,cls = OwnJSON))
  • 相关阅读:
    springcloud 微服务 分布式 Activiti6 工作流 vue.js html 跨域 前后分离
    java 整合redis缓存 SSM 后台框架 rest接口 shiro druid maven bootstrap html5
    继承
    封装
    对象的生命周期
    类与对象
    如何理解类?
    面向过程
    jdk1.8新特性
    git使用指南
  • 原文地址:https://www.cnblogs.com/ITchemist/p/11311713.html
Copyright © 2011-2022 走看看