Python实现支持JSON存储和解析的对象

来源:互联网 发布:keep软件使用步骤 编辑:程序博客网 时间:2024/05/17 01:57

我们知道利用JSON模块可方便的将Python基本类型(dict、list等)数据永久的存储成文件,同时也可以通过自定义转换函数和继承JSON encode&decode的方法实现自定义类的存储。本文就在前文“ Python JSON模块”的基础上,实现python支持JSON存储的对象。

对象能够采取JSON存储和解析是有很大意义的。例如机器学习中所有分类算法的训练过程中都存在大量的数据计算,如果每次启动分类都需要重新训练分类算法浪费资源且没有效率,如果能够将训练产生的分类算法对象保存起来,那么除非需要算法调优,以后只需载入即可。另一方面,对象能够进行JSON解析和存储也使得其可以在网络上传送,这在当下云计算、分布式数据处理中都有非凡的意义。

为了实现自存储和解析,定义对象的关键操作有:

0,将object_json.py copy至包中,定义对象的模块导入object_json:import object_json。

1,__init__()函数要支持可变数量的函数调用,即要写成__init__(self, ..., , **args)。如此定义对象才可以有除构造阶段需要初始化的属性之外的属性。

2,对于对象构造阶段必须初始化的属性,__init__()函数中的形参必须与这些属性名称完全相同,如此才能通过字典‘key’: value对构造对象。

3,定义一个属性‘__name__’--该对象实例的名称,利用inspect模块实现。‘__name__‘属性主要用于产生对象存储时默认的文件名称。

4,定义jsonDumps()和jsonLoadTransfer()方法,通过objectLoadFromFile()完成对象JSON文件load和新对象创建。

(i)jsonDumps()用于将对象转换成dict并通过json.dumps()将对象存储成json文件,若用户不指定文件名则以instancename.json为默认存储文件。由于JSON只支持python基本类型,因此若对象中有一些其他类型(如numpy matrix),则需将其转化成Python基本类型(如matrix.tolist()将matrix转换成list)。

(ii)jsonLoadTransfer()用于完成数据格式的转换,将一些对象属性从基本类型转化成需要的类型(如mat(list)将类型从list转换成matrix),若对象只有Python基本类型则可以省略该方法。创建完整、可用对象过程是:

  1. obj = objectLoadFromFile()   
  2. obj.jsonLoadTransfer()  

下面的代码就是支持自定义对象进行JSON存储和解析的object_json模块源码。

Source Code:▼Copy
  1. import json   
  2. import inspect    
  3. import pdb   
  4. def object2dict(obj):      
  5.     #convert object to a dict     
  6.     d = {'__class__':obj.__class__.__name__, '__module__':obj.__module__}      
  7.     d.update(obj.__dict__)      
  8.     return d   
  9. def objectDumps2File(obj, jsonfile):   
  10.     objDict = object2dict(obj)   
  11.     with open(jsonfile, 'w') as f:   
  12.         f.write(json.dumps(objDict))   
  13.        
  14. def dict2object(d):      
  15.     '''convert dict to object, the dict will be changed'''       
  16.     if'__class__' in d:      
  17.         class_name = d.pop('__class__')      
  18.         module_name = d.pop('__module__')      
  19.         module = __import__(module_name)      
  20.         #print 'the module is:', module     
  21.         class_ = getattr(module,class_name)      
  22.         args = dict((key.encode('ascii'), value) for key, value in d.items()) #get args    
  23.         #print 'the atrribute:', repr(args)  
  24.         #pdb.set_trace()   
  25.         inst = class_(**args) #create new instance     
  26.     else:      
  27.         inst = d      
  28.     return inst   
  29. def objectLoadFromFile(jsonFile):   
  30.     '''load json file and generate a new object instance whose __name__ filed 
  31.     will be 'inst' '''  
  32.     with open(jsonFile) as f:   
  33.         objectDict =json.load(f)   
  34.     obj = dict2object(objectDict)   
  35.     return obj   
  36. #test function      
  37. if __name__  == '__main__':   
  38.     class Person(object):      
  39.         def __init__(self,name,age, **args):   
  40.             obj_list = inspect.stack()[1][-2]   
  41.             self.__name__ = obj_list[0].split('=')[0].strip()#object instance name  
  42.             self.name = name      
  43.             self.age = age   
  44.                
  45.         def __repr__(self):      
  46.             return 'Person Object name : %s , age : %d' % (self.name,self.age)   
  47.         def say(self):   
  48.             #d = inspect.stack()[1][-2]  
  49.             #print d[0].split('.')[0].strip()  
  50.             return self.__name__  
  51.         def jsonDumps(self, filename=None):   
  52.             '''essential transformation to Python basic type in order to 
  53.             store as json. dumps as objectname.json if filename missed '''  
  54.             if not filename:   
  55.                 jsonfile = self.__name__+'.json'   
  56.             else: jsonfile = filename   
  57.             objectDumps2File(self, jsonfile)   
  58.            
  59.         def jsonLoadTransfer(self):#TBD  
  60.             '''essential transformation to object required type,such as 
  61.             numpy matrix.call this function after newobject = objectLoadFromFile(jsonfile)'''  
  62.             pass  
  63.   
  64.     p = Person('Aidan',22)        
  65.     #json.dumps(p)#error will be throwed  
  66.        
  67.     #objectDumps2File(p,'Person.json')  
  68.     p.jsonDumps()   
  69.     p_l = objectLoadFromFile('p.json')   
  70.          
  71.     print 'the decoded obj type: %s, obj:%s' % (type(p_l),repr(p_l))  

Python类有新旧两种,py 2.2 后类定义继承 object 的目的是使这个类成为 new style class, 没有继承 object 的为传统classic class(最终也会继承object)。

类定义中如下两种方法:

Source Code:▼Copy
  1. class Person():   
  2. class Person(object)   

其区别在于:

若创建新的Person instanc test,则type(test)的输出分别为:

Source Code:▼Copy
  1. <type 'instance'>   
  2. <class '__main__.Person'>  

inspect 模块提供了一系列自省函数,它可以获取模块,类,方法,函数,traceback,帧对象,代码对象的信息。常用的方法getmembers,ismodule,getcallargs,isclass等,更多详细信息参见http://docs.python.org/library/inspect.html。可以参考’python inspect模块解析

2 0
原创粉丝点击