Package: jsonizer
jsonizerIt is a library for parsing nested JSONs into predefined classes 🔨✨In many cases you can usedataclassesorpydanticfor parsing JSON into Python classes.
But sometimes you need to parse JSON into some predefined classes.
You can't change this classes, or it is too time-consuming.
For example, this classes can be imported from another library.
In this case, this is an ideal solution for you :)Reasons to use jsonizerSupports nested classesFastest class detectionNo dependenciesInstallationpipinstalljsonizerUsage samplefromjsonizerimportJsonizerclassEgg:def__init__(self,size,color='white'):self._size=sizeself._color=colordef__repr__(self):returnf'{self._color}egg with size{self._size}'classBird:def__init__(self,name,eggs):self._name=nameself._eggs=eggsdef__repr__(self):returnf'Bird "{self._name}" with eggs{self._eggs}'json_data={'name':'Duck','eggs':[{'size':12,},{'size':69,'color':'purple',}]}parser=Jsonizer(Bird,Egg)bird=parser.parse(json_data)print(bird)# >>> Bird "Duck" with eggs [white egg with size 12, purple egg with size 69]This sample can be foundhere.
For simplicity, there are no type hints (and no PEP8 style).
Butjsonizerallows and insists on using type hints.Hereis same sample but with type hintsParsing initial argumentsClassJsonizerrequire the list of classes in that JSONs can be parsed as first argument,
they can be in any orderOptional argumentsNameTypeDefaultDescriptionignore_ambiguityboolFalseIgnore exceptions when dicts can be matched to two or more constructors (see exceptions block)disallow_dictsboolFalseDisallow to have dict as class argument (see exceptions block)lowercase_keysboolFalseLowercase all keys (names) in input JSONreplace_spacestrNoneIf notNone, replace space in keys (names) in input JSON with this valueParsing functionsFunctionDescriptionSampleparse(dict/list)Parse object of list of objectsparse({'name': 'Alice'})parse_string(str)Parse JSON stringparse('{"name": "Alice"}')parse_file(str)Parse JSON file by filenameparse('sample.json')ExceptionsThere are 3+1 kind of exceptions:1. AmbiguityParamsExceptionIt appears whenjsonizertwo classes can have common init params.
In example below, json data{"name": "Alice"}can be matched to both classes.
You can ignore such situations by passingignore_ambiguity=Trueto parserclassPerson:def__init__(self,name:str):# .. some logic ...classWorker:def__init__(self,name:str,income:int=0):# .. some logic ...parser=Jsonizer(Worker,Person)# >>> jsonizer.exceptions.AmbiguityParamsException: Some signatures can be matched to class "<class 'sample.Worker'>" and "<class 'sample.Person'>" simultaneouslyparser=Jsonizer(Worker,Person,ignore_ambiguity=True)parser.parse(...)2. UnparsedJsonExceptionIn somerarely cases(I really don't know why) you may want to not have dicts as arguments.
You can reach this by passingdisallow_dicts=Trueto parserclassPerson:def__init__(self,name:str,contacts:Any):# .. some logic ...person_data={'name':'Alice','contacts':{'phone':'123-456-7890'}}parser=Jsonizer(Person,disallow_dicts=True)parser.parse(person_data)# >>> jsonizer.exceptions.UnparsedJsonException: Cannot recognize class for JSON data "{'phone': '123-456-7890'}"parser=Jsonizer(Person)person=parser.parse(person_data)# >> Hi! I am Alice, my contacts are {'phone': '123-456-7890'}3. FullyUnparsedExceptionCannot parse main dict (root/first elements) into one of passed classes.
Check keys of JSON data, is they really matched to any class4. JSONDecodeError (standard Python exception)Default Python exception in case of invalid JSON file or string.
Check your JSON, 99.69% that it is invalid. You can check ithere.
See more indocumentationPS in JSON you must use double quotes"instead of single', andnullinstead ofNoneFAQQ: Why is it so fast?A: It uses hashes to represent all possible constructor (regardless the arguments order)Q: What does parser do withself,*argsand**kwargs?A: It skips them, even if they have different nameQ: Where there are so few tests?A: They are waiting while you will code them :)MorePyPI:https://pypi.org/project/jsonizerRepository:https://github.com/abionics/jsonizerDeveloper: Alex Ermolaev (Abionics)Email:abionics.dev@gmail.comLicense: MIT (see LICENSE.txt)