Package: jsonconversion
ThejsonconversionpackageThis python module helps converting arbitrary Python objects into JSON strings and back. It extends the basic features
of theJSONEncoderandJSONDecoderclasses provided by the nativejsonpackage. For this purpose,jsonconversionships with these four classes:TheJSONObjectclassYour serializable classes should inherit from this class. Hereby, they must implement the methodsfrom_dictandto_dict. The example further down describes how to do so.TheJSONExtendedEncoderclassThis is a class used internally byJSONObjectEncoder. However, it can also be used directly, if you do not need the
features ofJSONObjectEncoderbut want to implement your own encoders.The class is especially helpful, if you want custom handling of builtins (int,dict, …) or classes deriving
from builtins. This would not be possible if directly inheriting fromJSONEncoder. To do so, override theisinstancemethod and returnFalsefor all types you want to handle in thedefaultmethod.If you look at the source code ofJSONObjectEncoder, you will see how this can be used.TheJSONObjectEncoderclassEncodes Python objects into JSON strings. Supported objects are:Python builtins:int,float,str,list,set,dict,tupletypeobjects:isinstance(object, type)All classes deriving fromJSONObjectThose objects can of course also be nested!TheJSONObjectDecoderclassDecodes JSON strings converted using theJSONObjectEncoderback to Python objects.The class adds a custom keyword argument to theload[s]method:substitute_modules. This parameter takes adictin the form{"old.module.MyClass": "new.module.MyClass"}. It can be used if you have serializedJSONObjects who’s module path has changed.UsageUsingjsonconversionis easy. You can find further code examples in thetestfolder.Encoding and DecodingIn order to encode Python objects with JSON conversion and to later decode them, you have to import the Python modulejson. The module provides the methodsdump/dumpsfor encoding andload/loadsfor decoding:importjsonfromjsonconversion.decoderimportJSONObjectDecoderfromjsonconversion.encoderimportJSONObjectEncodervar=(1,2,3)# variable to be serialized# "dumps" converts the variable to a string, "dump" directly writes it to a filestr_var=json.dumps(var,cls=JSONObjectEncoder)# Equivalently, "loads" converts the object back from a string. "load" from a filevar_2=json.loads(str_var,cls=JSONObjectDecoder)assertvar==var_2Deriving from JSONObjectIn order to serialize arbitrary, self-written classes, they must derive fromJSONObjectand implement the two
methodsfrom_dictandto_dict:classMyClass(JSONObject):def__init__(self,a,b,c):self.a=aself.b=bself.c=c@classmethoddeffrom_dict(cls,dict_):returncls(dict_['a'],dict_['b'],dict_['c'])defto_dict(self):return{'a':self.a,'b':self.b,'c':self.c}def__eq__(self,other):returnself.a==other.aandself.b==other.bandself.c==other.cGeneral notesjsonconversionstores the class path in the JSON string when serializing a JSONObject. When decoding the object
back, it automatically imports the correct module. You only have to ensure that the module is within yourPYTHONPATH.Theto_dictandfrom_dictmethods only need to specify the elements of a class, needed to recreate the
object. Derived attributes of a class (likeagefromyear_born) do not need to be serialized.If you compare the original object with the object obtained from serialization and deserialization usingis, they
will differ, as these are objects at different locations in memory. Also a comparison of JSONObject with==will
fail, if you do not tell Python how to compare two objects. This is whyMyClassoverrides the__eq__method.