Package: dc-json
DC JSONThis library provides a simple API for encoding and decodingdataclassesto and from JSON.It's recursive (see caveats below), so you can easily work with nested dataclasses.
In addition to the supported types in thepy to JSON table, this library supports the following:any arbitraryCollectiontype is supported.Mappingtypes are encoded as JSON objects andstrtypes as JSON strings.
Any other Collection types are encoded into JSON arrays, but decoded into the original collection types.datetimeobjects.datetimeobjects are encoded tofloat(JSON number) usingtimestamp.
As specified in thedatetimedocs, if yourdatetimeobject is naive, it will
assume your system local timezone when calling.timestamp(). JSON nunbers
corresponding to adatetimefield in your dataclass are decoded
into a datetime-aware object, withtzinfoset to your system local timezone.
Thus, if you encode a datetime-naive object, you will decode into a
datetime-aware object. This is important, because encoding and decoding won't
strictly be inverses. See this section if you want to override this default
behavior (for example, if you want to use ISO).UUIDobjects. They
are encoded asstr(JSON string).Thelatest releaseis compatible with both Python 3.7 and Python 3.6 (with the dataclasses backport).Quickstartpip install dc-jsonApproach 1: Class decoratorfromdataclassesimportdataclassfromdc_jsonimportdataclass_json@dataclass_json@dataclassclassPerson:name:strlidatong=Person('lidatong')# Encoding to JSONlidatong.to_json()# '{"name": "lidatong"}'# Decoding from JSONPerson.from_json('{"name": "lidatong"}')# Person(name='lidatong')Note that the@dataclass_jsondecorator must be stacked above the@dataclassdecorator (order matters!)Approach 2: Inherit from a mixinfromdataclassesimportdataclassfromdc_jsonimportDataClassJsonMixin@dataclassclassPerson(DataClassJsonMixin):name:strlidatong=Person('lidatong')# A different example from Approach 1 above, but usage is the exact sameassertPerson.from_json(lidatong.to_json())==lidatongPick whichever approach suits your taste. The differences in implementation are
invisible in usage.How do I...Use my dataclass with JSON arrays or objects?fromdataclassesimportdataclassfromdc_jsonimportdataclass_json@dataclass_json@dataclassclassPerson:name:strEncode into a JSON array containing instances of my Data Classpeople_json=[Person('lidatong')]Person.schema().dumps(people_json,many=True)# '[{"name": "lidatong"}]'Decode a JSON array containing instances of my Data Classpeople_json='[{"name": "lidatong"}]'Person.schema().loads(people_json,many=True)# [Person(name='lidatong')]Encode as part of a larger JSON object containing my Data Class (e.g. an HTTP
request/response)importjsonperson_dict=Person.schema().dump(Person('lidatong'))response_dict={'response':{'person':person_dict}}response_json=json.dumps(response_dict)In this case, we do two steps. First, we encode the dataclass into apython dictionaryrather than a JSON string, usingschema()anddump.
Scroll down for a section addressing that.Second, we leverage the built-injson.dumpsto serialize ourdataclassinto
a JSON string.Decode as part of a larger JSON object containing my Data Class (e.g. an HTTP
response)importjsonresponse_dict=json.loads('{"response": {"person": {"name": "lidatong"}}}')person_dict=response_dict['response']person=Person.schema().load(person_dict)In a similar vein to encoding above, we leverage the built-injsonmodule.First, calljson.loadsto read the entire JSON object into a
dictionary. We then access the key of the value containing the encoded dict of
ourPersonthat we want to decode (response_dict['response']).Second, we load in the dictionary usingPerson.schema().load.Encode or decode into Python lists/dictionaries rather than JSON?This can be by calling.schema()and then using the corresponding
encoder/decoder methods, ie..load(...)/.dump(...).Encode into a single Python dictionaryperson=Person('lidatong')Person.schema().dump(person)# {"name": "lidatong"}Encode into a list of Python dictionariespeople=[Person('lidatong')]Person.schema().dump(people,many=True)# [{"name": "lidatong"}]Decode a dictionary into a single dataclass instanceperson_dict={"name":"lidatong"}Person.schema().load(person_dict)# Person(name='lidatong')Decode a list of dictionaries into a list of dataclass instancespeople_dicts=[{"name":"lidatong"}]Person.schema().load(people_dicts,many=True)# [Person(name='lidatong')]Handle missing or optional field values when decoding?By default, any fields in your dataclass that usedefaultordefault_factorywill have the values filled with the provided default, if the
corresponding field is missing from the JSON you're decoding.Decode JSON with missing field@dataclass_json@dataclassclassStudent:id:intname:str='student'Student.from_json('{"id": 1}')# Student(id=1, name='student')Noticefrom_jsonfilled the fieldnamewith the specified default 'student'
when it was missing from the JSON.Sometimes you have fields that are typed asOptional, but you don't
necessarily want to assign a default. In that case, you can use theinfer_missingkwarg to makefrom_jsoninfer the missing field value asNone.Decode optional field without default@dataclass_json@dataclassclassTutor:id:intstudent:Optional[Student]Tutor.from_json('{"id": 1}')# Tutor(id=1, student=None)Personally I recommend you leverage dataclass defaults rather than usinginfer_missing, but if for some reason you need to decouple the behavior of
JSON decoding from the field's default value, this will allow you to do so.ExplanationBriefly, on what's going on under the hood in the above examples: calling.schema()will have this library generate amarshmallow schemafor you. It also fills in the corresponding object hook, so that marshmallow
will create an instance of your Data Class onload(e.g.Person.schema().loadreturns aPerson) rather than adict, which it does
by default in marshmallow.Performance note.schema()is not cached (it generates the schema on every call), so if you
have a nested Data Class you may want to save the result to a variable to
avoid re-generation of the schema on every usage.person_schema=Person.schema()person_schema.dump(people,many=True)# later in the code...person_schema.dump(person)Override the default encode / decode / marshmallow field of a specific field?SeeOverridingMarshmallow interopUsing thedataclass_jsondecorator or mixing inDataClassJsonMixinwill
provide you with an additional method.schema()..schema()generates a schema exactly equivalent to manually creating a
marshmallow schema for your dataclass. You can reference themarshmallow API docsto learn other ways you can use the schema returned by.schema().You can pass in the exact same arguments to.schema()that you would when
constructing aPersonSchemainstance, e.g..schema(many=True), and they will
get passed through to the marshmallow schema.fromdataclassesimportdataclassfromdc_jsonimportdataclass_json@dataclass_json@dataclassclassPerson:name:str# You don't need to do this - it's generated for you by `.schema()`!frommarshmallowimportSchema,fieldsclassPersonSchema(Schema):name=fields.Str()Overriding / ExtendingOverridingFor example, you might want to encode/decodedatetimeobjects using ISO format
rather than the defaulttimestamp.fromdataclassesimportdataclass,fieldfromdc_jsonimportdataclass_jsonfromdatetimeimportdatetimefrommarshmallowimportfields@dataclass_json@dataclassclassDataClassWithIsoDatetime:created_at:datetime=field(metadata={'dc_json':{'encoder':datetime.isoformat,'decoder':datetime.fromisoformat,'mm_field':fields.DateTime(format='iso')}})ExtendingSimilarly, you might want to extenddc_jsonto encodedateobjects.fromdataclassesimportdataclass,fieldfromdc_jsonimportdataclass_jsonfromdatetimeimportdatefrommarshmallowimportfields@dataclass_json@dataclassclassDataClassWithIsoDatetime:created_at:date=field(metadata={'dc_json':{'encoder':date.isoformat,'decoder':date.fromisoformat,'mm_field':fields.DateTime(format='iso')}})As you can see, you canoverrideorextendthe default codecs by providing a "hook" via a
callable:encoder: a callable, which will be invoked to convert the field value when encoding to JSONdecoder: a callable, which will be invoked to convert the JSON value when decoding from JSONmm_field: a marshmallow field, which will affect the behavior of any operations involving.schema()Note that these hooks will be invoked regardless if you're using.to_json/dump/dumpsand.from_json/load/loads. So apply overrides / extensions judiciously, making sure to
carefully consider whether the interaction of the encode/decode/mm_field is consistent with what you expect!A larger examplefromdataclassesimportdataclassfromdc_jsonimportdataclass_jsonfromtypingimportList@dataclass_json@dataclass(frozen=True)classMinion:name:str@dataclass_json@dataclass(frozen=True)classBoss:minions:List[Minion]boss=Boss([Minion('evil minion'),Minion('very evil minion')])boss_json="""{"minions": [{"name": "evil minion"},{"name": "very evil minion"}]}""".strip()assertboss.to_json(indent=4)==boss_jsonassertBoss.from_json(boss_json)==bossCaveatsData Classes that contain forward references (e.g. recursive dataclasses) are
not currently supported.