Python implements objects that support JSON storage and parsing, and pythonjson
We know that the JSON module can be used to conveniently store basic Python data (such as dict and list) as files permanently, at the same time, you can use custom conversion functions and methods that inherit JSON encode & decode to store custom classes. This article is based on the previous article "Python JSON module" to implement python objects that support JSON storage.
It is of great significance that objects can be stored and parsed in JSON format. For example, a large amount of data computing exists in the training process of all classification algorithms in machine learning. If you need to re-train the classification algorithm every time you start classification, this is a waste of resources and inefficient, if you can save the classification algorithm objects generated by training, you only need to load them later unless you need algorithm optimization. On the other hand, objects can be parsed and stored in JSON format so that they can be transmitted over the network. This is of extraordinary significance in cloud computing and distributed data processing.
To achieve custom storage and resolution, key operations for defining objects include:
0. copy object_json.py to the package and import the module of the defined object to object_json: import object_json.
1 ,__ init _ () The function must support variable number of function calls, that is, it must be written as _ init _ (self,..., ** args ). So that the defined object can have attributes other than those that need to be initialized during the construction phase.
2. For attributes that must be initialized in the object construction phase, the form parameters in the __init _ () function must be identical with these attribute names so that the dictionary 'key' can be used ': value Pair.
3. Define an attribute '_ name _' -- name of the object instance, which is implemented using the inspect module. The '_ name _' attribute is mainly used to generate the default file name for Object Storage.
4. Define the jsonDumps () and jsonLoadTransfer () methods and use objectLoadFromFile () to load the object JSON file and create the new object.
(I) jsonDumps () is used to convert an object to dict and use json. dumps () Stores objects as json files. If you do not specify a file name, the object is stored as instancename. json is the default storage file. JSON only supports python basic types. Therefore, if the object contains some other types (such as numpy matrix), you need to convert it to Python basic types (such as matrix. tolist () converts a matrix to a list ).
(Ii) jsonLoadTransfer () is used to convert the data format and convert some object attributes from the basic type to the desired type (such as mat (list) to convert the type from list to matrix ), this method can be omitted if the object only has the Python basic type. Complete and available object creation process:
- Obj = objectLoadFromFile ()
- Obj. jsonLoadTransfer ()
The following code is the source code of the object_json module that supports JSON storage and parsing of custom objects.
Source Code: Invalid Copy
- Import json
- Import inspect
- Import pdb
- Def object2dict (obj ):
- # Convert object to a dict
- D = {'_ class _': obj. _ class _. _ name __, '_ module _': obj. _ module __}
- D. update (obj. _ dict __)
- Return d
- Def objectDumps2File (obj, jsonfile ):
- ObjDict = object2dict (obj)
- With open (jsonfile, 'w') as f:
- F. write (json. dumps (objDict ))
- Def dict2object (d ):
- '''Convert dict to object, the dict will be changed '''
- If '_ class _' in d:
- Class_name = d. pop ('_ class __')
- Module_name = d. pop ('_ module __')
- Module = _ import _ (module_name)
- # Print 'the module is: ', module
- Class _ = getattr (module, class_name)
- Args = dict (key. encode ('ascii '), value) for key, value in d. items () # get args
- # Print 'the atrriyun: ', repr (args)
- # Pdb. set_trace ()
- Inst = class _ (** args) # create new instance
- Else:
- Inst = d
- Return inst
- Def objectLoadFromFile (jsonFile ):
- '''Load json file and generate a new object instance whose _ name _ filed
- Will be 'instance ''''
- With open (jsonFile) as f:
- ObjectDict = json. load (f)
- Obj = dict2object (objectDict)
- Return obj
- # Test function
- If _ name _ = '_ main __':
- Class Person (object ):
- Def _ init _ (self, name, age, ** args ):
- Obj_list = inspect. stack () [1] [-2]
- Self. _ name _ = obj_list [0]. split ('=') [0]. strip () # object instance name
- Self. name = name
- Self. age = age
- Def _ repr _ (self ):
- Return 'person Object name: % s, age: % d' % (self. name, self. age)
- Def say (self ):
- # D = inspect. stack () [1] [-2]
- # Print d [0]. split ('.') [0]. strip ()
- Return self. _ name __
- Def jsonDumps (self, filename = None ):
- '''Essential transformation to Python basic type in order
- Store as json. dumps as objectname. json if filename missed '''
- If not filename:
- Jsonfile = self. _ name _ + '. json'
- Else: jsonfile = filename
- ObjectDumps2File (self, jsonfile)
- Def jsonLoadTransfer (self): # TBD
- '''Essential transformation to object required type, such
- Numpy matrix. call this function after newobject = objectLoadFromFile (jsonfile )'''
- Pass
- P = Person ('aida', 22)
- # Json. dumps (p) # error will be throwed
- # ObjectDumps2File (p, 'person. json ')
- P. jsonDumps ()
- P_l = objectLoadFromFile ('p. json ')
- Print 'the decoded obj type: % s, obj: % s' % (type (p_l), repr (p_l ))
There are two types of Python classes: new and Old. After py 2.2, the class definition inherits the object to make this class A new style class, if the object is not inherited, It is a traditional classic class (and the object will be inherited ).
The following two methods are used in class definition:
Source Code: Invalid Copy
- Class Person ():
- Class Person (object)
The difference is:
If a new Person instanc test is created, the output of type (test) is as follows:
Source Code: Invalid Copy
- <Type 'instance'>
- <Class '_ main _. Person'>
The inspect module provides a series of introspection functions that can obtain information about modules, classes, methods, functions, traceback, Frame Objects, and code objects. Common methods include getmembers, ismodule, getcallargs, and isclass. For more information, see http://docs.python.org/library/inspect.html. Refer'Analysis of python inspect Module'