zoukankan      html  css  js  c++  java
  • json 对数据进行序列化时,对不是python基本数据类型进行序列化时,如对--对象、日期、时间等处理

    ''''

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import json as default_json
    from json.encoder import JSONEncoder


    class JsonEncoder(JSONEncoder):
    def default(self, o):
    if isinstance(o, object):
    return o.__dict__
    return JSONEncoder.default(self, o)


    class Json(object):

    @staticmethod
    def dumps(response, ensure_ascii=True):

    return default_json.dumps(response, ensure_ascii=ensure_ascii, cls=JsonEncoder)



    ''''

    import json
    from json.encoder import JSONEncoder
    from datetime import datetime,date
    
    class Jsonencoder(JSONEncoder):
        def default(self, field):
            if isinstance(field,datetime):    #如果field是日期类型
                return field.strftime("%Y-%m-%d %H:%M:%S")
            elif isinstance(field,date):
                return field.strftime("%Y-%m-%d")
            elif isinstance(field,object):
                return field.__dict__
            else:
                return json.JSONEncoder.default(self,field)
    
    class Baseobj():
        def __init__(self):
            self.status=True
            self.message=None
            self.data=None
            self.name="hello"
    #json序列化只能dumps py的基本数据类型:如字典,列表、数字,如日期、对象的话需要做特殊处理
    aa=Baseobj()
    print("----------",aa)   #<__main__.Baseobj object at 0x000002D941E97F48>
    data_obj={
        "k1":132,
        "k2":datetime.now(),
        "k3":Baseobj(),
        "k4":"hao",
      "k5":[
    "as", 2, "sadf"]
    }
    
    ds=json.dumps(data_obj,cls=Jsonencoder)
    print(ds)
    
    '''
    {"k1": 132,
    "k2": "2021-02-24 19:40:20",
    "k3": {"status": true, "message": null, "data": null, "name": "hello"},
    "k4": "hao",
    "k5": ["as", 2, "sadf"]
    }
    '''
  • 相关阅读:
    Nginx 之 Nginx配置实例——负载均衡
    Nginx 之 Nginx配置实例——反向代理
    OverFeat:Integrated Recognition, Localization and Detection using Convolutional Networks
    Fourier Transform
    Pytest中使用pytest.exit中断用例执行
    Pytest自定义测试报告
    idea spring源码踩坑日记
    数据结构笔记八:排序
    数据结构笔记七:查找
    数据结构笔记六:图
  • 原文地址:https://www.cnblogs.com/longyi2020/p/14443461.html
Copyright © 2011-2022 走看看