python json 自定义编码解码函数

直接上代码

自定义的编码解码函数,这里以时间类型的数据编码解码为例

def json_decode_datetime(obj):
    if isinstance(obj, datetime):
        return {
    
    
            "json_decode_datetime":  datetime.timestamp(obj)
        }
    return obj


def json_encode_datetime(dic):
    if dic.get("json_decode_datetime", None):
        return datetime.fromtimestamp(dic['json_decode_datetime'])
    return dic

json调用编码解码函数

dict_data = json.loads(cache, object_hook=json_encode_datetime)
res_str = json.dumps(frame_full_info.dict(), default=json_decode_datetime)

猜你喜欢

转载自blog.csdn.net/Defiler_Lee/article/details/118299477
今日推荐