Python Json操作封装的基本实现

#!/usr/bin/env python3
# -*- coding= UTF-8 -*-

#    name=jsonconfig
#    version=0.0.1
#    packages=
#    author=singebogo
#    author_email=singbogo@163.com
#    date=20180427
#    description=  demjson 第三方库  使用 pip install demjson / Github 地址:https://github.com/dmeranda/demjson


import json, demjson
from new_frame.api.filegener.fileoperator.filebase import FileBase
from new_frame.api.exception.filenotfound import FileNotFoundError
from new_frame.util.logutil.log import logger


class JsonConfig(object):
    '''
        1、对json进行序列化,反序列化,一次性的dump和load持久化文件  
        2、 #自定义数据类型的序列化/反序列化
		 #要实现自定义数据类型的序列化与反序列化有两种方式:
			# 1、通过转换函数实现
			# 2、通过继承JSONEncoder和JSONDecoder类实现
    '''
    def __init__(self,file=None, dict={}):
        self.dict = dict
        self.file = file


    # 序列化
    def Dumps(self, dict={}):
        try:
            if dict is None:
                return json.dumps(self.dict)
            else:
                return json.dumps(dict)
        except BaseException as baseerr:
            logger.error(baseerr.message)
            print (baseerr.message)

    # 反序列化
    def Loads(self, dict={}):
        try:
            if dict is None:
                return json.loads(self.dict)
            else:
                return json.loads(dict)
        except BaseException as baseerr:
            logger.error(baseerr.message)
            print (baseerr.message)

    # 序列化到文件中
    def Write(self, dict={}, mode='w',indent=4):
        '''
        @param mode:文件打开模式 默认参数为w
        @param indent:
         @param dict: 需要dump的字典
        @return:返回None json写入文件成功
        '''
        if self.file is not None:
            with open(self.file, mode) as fp:
                if dict is None:
                    return json.dump(self.dict, fp, indent)
                else:
                    return json.dump(dict, fp, indent)

    # 反序列化文件中的内容
    def Read(self, mode = 'r'):
        '''
        @param mode: 文件打开模式 默认参数为r
        @return:返回dict
        '''
        if self.file is not None:
            if FileBase(self.file).isExist(None):
                try:
                    with open(self.file, mode) as fp:
                        return json.load(fp)
                except OSError as oserr:
                    print (oserr)
                    logger.error(oserr.message + "Json Read Error")
            else:
                logger.error(self.file + "not exits")
                raise FileNotFoundError(self.file + "not exits")
    # 自定义数据类型的序列化/反序列化
    # 方法1:编写转换函数
    '''
    def obj2dict(obj):
        d = {}
        d['__class__'] = obj.__class__.__name__
        d['__module__'] = obj.__module__
        d.update(obj.__dict__)
        return d

    def dict2obj(d):
        if '__class__' in d:
            class_name = d.pop('__class__')
            module_name = d.pop('__module__')
            module = __import__(module_name)
            class_ = getattr(module, class_name)
            args = dict((key.encode('ascii'), value) for key, value in d.items())
            instance = class_(**args)
        else:
            instance = d
        return instance
    '''

    #方法2 继承JSONEncoder和JSONDecoder实现子类
    class MyJSONEncoder(json.JSONEncoder):
        def default(self, obj):
            d = {}
            d['__class__'] = obj.__class__.__name__
            d['__module__'] = obj.__module__
            d.update(obj.__dict__)
            return d

    class MyJSONDecoder(json.JSONDecoder):
        def __init__(self):
            json.JSONDecoder.__init__(self, object_hook=self.dict2obj)

        def dict2obj(self, d):
            if '__class__' in d:
                class_name = d.pop('__class__')
                module_name = d.pop('__module__')
                module = __import__(module_name)
                class_ = getattr(module, class_name)
                args = dict((key.encode('ascii'), value) for key, value in d.items())
                instance = class_(**args)
            else:
                instance = d
            return instance


if __name__ == '__main__':
    class Student(object):
        def __init__(self, name, age, sno):
            self.name = name
            self.age = age
            self.sno = sno

        def __repr__(self):
            return 'Student [name: %s, age: %d, sno: %d]' % (self.name, self.age, self.sno)

    jsonconfig = JsonConfig('test.json', {'a': 'str中国', 'c': True, 'e': 10, 'b': 11.1, 'd': None, 'f': [1, 2, 3], 'g': (4, 5, 6)})
    print (jsonconfig.Write())
    encode = jsonconfig.Read()
    print (jsonconfig.Dumps())    #空字典
    decode = jsonconfig.Dumps(encode)
    print (jsonconfig.Loads())    #空字典
    print (jsonconfig.Loads(decode))

    stu = Student('Tom', 19, 1)
    #方式一:直接调用子类MyJSONEncoder的encode()方法进行序列化
    print (JsonConfig.MyJSONEncoder().encode(stu))
    print (JsonConfig.MyJSONEncoder(separators=(',', ':')).encode(stu))
    # 方式二:将子类MyJSONEncoder作为cls参数的值传递给json.dumps()函数
    objencode = json.dumps(stu, cls=JsonConfig.MyJSONEncoder)
    print ("---------------------")
    print (jsonconfig.Write(objencode))
    print (json.dumps(stu, cls=JsonConfig.MyJSONEncoder, separators=(',', ':')))
    # 反序列化测试:
    print (JsonConfig.MyJSONDecoder().decode('{"sno": 1, "__module__": "__main__", "age": 19, "__class__": "Student", "name": "Tom"}'))
    print (JsonConfig.MyJSONDecoder().decode(objencode))
    print (jsonconfig.Read())



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值