Package: pykson
Pykson: A JSON Serializer/Deserializer for PythonPykson is a JSON serializer/deserializer in python.Tested with:Python 3.6+Use the following command to install using pip:pip install pyksonUsage exampleCreate Object ModelsFirst, create your object model which extendsJsonObjectfrompyksonimportJsonObject,IntegerField,StringField,ObjectListFieldclassCourse(JsonObject):name=StringField()teacher=StringField()classScore(JsonObject):score=IntegerField()course=Course()classStudent(JsonObject):first_name=StringField()last_name=StringField()age=IntegerField()scores=ObjectListField(Score)Deserialize json stringsUsePyksonclass to deserialize json string toJsonObjectsfrompyksonimportPyksonjson_text='{"first_name":"John", "last_name":"Smith", "age": 25, "scores": [ {"course": {"name": "Algebra", "teacher" :"Mr. Schmidt"}, "score": 100}, {"course": {"name": "Statistics", "teacher": "Mrs. Lee"}, "score": 90} ]}'student=Pykson().from_json(json_text,Student)Serialize objectsUsePyksonclass to serializeJsonObjects to stringPykson().to_json(student)FieldsThere are different types of predefined fields:IntegerField,FloatField,BooleanField,StringField,ListField,ObjectField,ObjectListField,DateField,TimeField,DateTimeField,TimestampSecondsFieldandTimestampMillisecondsField.There are four other types of fields which help with storing fields with specific integer or string values. To create a field with multiple choice integer values, useMultipleChoiceIntegerFieldorEnumIntegerFieldclasses. To create a field with multiple choice string values, useMultipleChoiceStringFieldorEnumStringFieldclasses.Example forMultipleChoiceStringField:frompyksonimportMultipleChoiceStringFieldclassWeatherInfo(JsonObject):condition=MultipleChoiceStringField(options=['sunny','cloudy','rainy'],null=False)Example forEnumStringField:fromenumimportEnumfrompyksonimportEnumStringFieldclassWeatherCondition(Enum):SUNNY='sunny'CLOUDY='cloudy'RAINY='rainy'classWeatherInfo(JsonObject):condition=EnumStringField(enum=WeatherCondition,null=False)Advanced usageSerialized namesIt is possible to use change name of fields during serialization/deserialization. For this purpose, useserialized_nameinput in the fieldsfrompyksonimportPykson,JsonObject,IntegerField,StringField,ObjectFieldclassScore(JsonObject):score=IntegerField(serialized_name="s")course=StringField(serialized_name="c")classStudent(JsonObject):first_name=StringField(serialized_name="fn")last_name=StringField(serialized_name="ln")age=IntegerField(serialized_name="a")score=ObjectField(Score,serialized_name="s")json_text='{"fn":"John", "ln":"Smith", "a": 25, "s": {"s": 100, "c":"Algebra"}}'student=Pykson().from_json(json_text,Student)Work with dates and datetimesPykson currenty has five fields for handlingdates anddatetimes.
Three of them,DateField,TimeFieldandDateTimeField, use date/time formats to serialize/deserialize values. The other ones,TimestampSecondsFieldandTimestampMillisecondsFielduse integer values to serialize/deserialize datetimes.Accept unknown key/value pairs when deserializingfrom_jsonmethod currently has an input parameter namedaccept_unknownwith default value offalse. If you want to deserialize an string to aJsonObjectand ignore unknown keys which are not defined in your model class as fields, you can set this parameter totrue. If this parameter is false, an error is raised when facing an unknown key in the json.json_text='{"fn":"John", "ln":"Smith", "a": 25, "up":"some unknown parameter", "s": {"s": 100, "c":"Algebra"}}'student=Pykson().from_json(json_text,Student,accept_unknown=True)Type hierarchy adapterYou can register multiple type hierarchy adapters using register_type_hierarchy_adapter method of 'Pykson' class.frompyksonimportTypeHierarchyAdapterclassStudent(JsonObject):name=StringField(serialized_name="n")classHighSchoolStudent(Student):high_school_name=StringField(serialized_name="sn")classUniversityStudent(Student):university_name=StringField(serialized_name="un")students=[HighSchoolStudent(name="john",high_school_name="Redstone High"),UniversityStudent(name="alice",university_name="Green Institute of Tech.")]pson=Pykson()pson.register_type_hierarchy_adapter(Student,"student_type",{"highschool":HighSchoolStudent,"university":UniversityStudent})students_json=pson.to_json(students)decoded_students=pson.from_json(students_json,Student)assertdecoded_students==students