Package: dataclasses-json-speakeasy
Dataclasses JSONThis library provides a simple API for encoding and decodingdataclassesto and from JSON.It's very easy to get started.README / Documentation website. Features a navigation bar and search functionality, and should mirror this README exactly -- take a look!Quickstartpip install dataclasses-jsonfromdataclassesimportdataclassfromdataclasses_jsonimportdataclass_json@dataclass_json@dataclassclassPerson:name:strperson=Person(name='lidatong')person.to_json()# '{"name": "lidatong"}' <- this is a stringperson.to_dict()# {'name': 'lidatong'} <- this is a dictPerson.from_json('{"name": "lidatong"}')# Person(1)Person.from_dict({'name':'lidatong'})# Person(1)# You can also apply _schema validation_ using an alternative API# This can be useful for "typed" Python codePerson.from_json('{"name": 42}')# This is ok. 42 is not a `str`, but# dataclass creation does not validate typesPerson.schema().loads('{"name": 42}')# Error! Raises `ValidationError`What if you want to work with camelCase JSON?# same imports as above, with the additional `LetterCase` importfromdataclassesimportdataclassfromdataclasses_jsonimportdataclass_json,LetterCase@dataclass_json(letter_case=LetterCase.CAMEL)# now all fields are encoded/decoded from camelCase@dataclassclassConfiguredSimpleExample:int_field:intConfiguredSimpleExample(1).to_json()# {"intField": 1}ConfiguredSimpleExample.from_json('{"intField": 1}')# ConfiguredSimpleExample(1)Supported typesIt'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 numbers
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. Seethis sectionif you want to override this default
behavior (for example, if you want to use ISO).UUIDobjects. They
are encoded asstr(JSON string).Decimalobjects. They are
also encoded asstr.Thelatest releaseis compatible with both Python 3.7 and Python 3.6 (with the dataclasses backport).UsageApproach 1: Class decoratorfromdataclassesimportdataclassfromdataclasses_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 mixinfromdataclassesimportdataclassfromdataclasses_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. Note that there is better support for
the mixin approach when usingstatic analysistools (e.g. linting, typing),
but the differences in implementation will be invisible inruntimeusage.How do I...Use my dataclass with JSON arrays or objects?fromdataclassesimportdataclassfromdataclasses_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)importjsonresponse_dict={'response':{'person':Person('lidatong').to_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, using.to_dict.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.from_dict(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.from_dict.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.to_dict()# {'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.from_dict(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')]Encode or decode from camelCase (or kebab-case)?JSON letter case by convention is camelCase, in Python members are by convention snake_case.You can configure it to encode/decode from other casing schemes at both the class level and the field level.fromdataclassesimportdataclass,fieldfromdataclasses_jsonimportLetterCase,config,dataclass_json# changing casing at the class level@dataclass_json(letter_case=LetterCase.CAMEL)@dataclassclassPerson:given_name:strfamily_name:strPerson('Alice','Liddell').to_json()# '{"givenName": "Alice"}'Person.from_json('{"givenName": "Alice", "familyName": "Liddell"}')# Person('Alice', 'Liddell')# at the field level@dataclass_json@dataclassclassPerson:given_name:str=field(metadata=config(letter_case=LetterCase.CAMEL))family_name:strPerson('Alice','Liddell').to_json()# '{"givenName": "Alice"}'# notice how the `family_name` field is still snake_case, because it wasn't configured abovePerson.from_json('{"givenName": "Alice", "family_name": "Liddell"}')# Person('Alice', 'Liddell')This library assumes your field follows the Python convention of snake_case naming.If your field is notsnake_caseto begin with and you attempt to parameterizeLetterCase,
the behavior of encoding/decoding is undefined (most likely it will result in subtle bugs).Encode or decode using a different namefromdataclassesimportdataclass,fieldfromdataclasses_jsonimportconfig,dataclass_json@dataclass_json@dataclassclassPerson:given_name:str=field(metadata=config(field_name="overriddenGivenName"))Person(given_name="Alice")# Person('Alice')Person.from_json('{"overriddenGivenName": "Alice"}')# Person('Alice')Person('Alice').to_json()# {"overriddenGivenName": "Alice"}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]=NoneTutor.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.Handle unknown / extraneous fields in JSON?By default, it is up to the implementation what happens when ajson_dataclassreceives input parameters that are not defined.
(thefrom_dictmethod ignores them, when loading usingschema()a ValidationError is raised.)
There are three ways to customize this behavior.Assume you want to instantiate a dataclass with the following dictionary:dump_dict={"endpoint":"some_api_endpoint","data":{"foo":1,"bar":"2"},"undefined_field_name":[1,2,3]}You can enforce to always raise an error by setting theundefinedkeyword toUndefined.RAISE('RAISE'as a case-insensitive string works as well). Of course it works normally if you don't pass any undefined parameters.fromdataclasses_jsonimportUndefined@dataclass_json(undefined=Undefined.RAISE)@dataclass()classExactAPIDump:endpoint:strdata:Dict[str,Any]dump=ExactAPIDump.from_dict(dump_dict)# raises UndefinedParameterErrorYou can simply ignore any undefined parameters by setting theundefinedkeyword toUndefined.EXCLUDE('EXCLUDE'as a case-insensitive string works as well). Note that you will not be able to retrieve them usingto_dict:fromdataclasses_jsonimportUndefined@dataclass_json(undefined=Undefined.EXCLUDE)@dataclass()classDontCareAPIDump:endpoint:strdata:Dict[str,Any]dump=DontCareAPIDump.from_dict(dump_dict)# DontCareAPIDump(endpoint='some_api_endpoint', data={'foo': 1, 'bar': '2'})dump.to_dict()# {"endpoint": "some_api_endpoint", "data": {"foo": 1, "bar": "2"}}You can save them in a catch-all field and do whatever needs to be done later. Simply set theundefinedkeyword toUndefined.INCLUDE('INCLUDE'as a case-insensitive string works as well) and define a field
of typeCatchAllwhere all unknown values will end up.
This simply represents a dictionary that can hold anything.
If there are no undefined parameters, this will be an empty dictionary.fromdataclasses_jsonimportUndefined,CatchAll@dataclass_json(undefined=Undefined.INCLUDE)@dataclass()classUnknownAPIDump:endpoint:strdata:Dict[str,Any]unknown_things:CatchAlldump=UnknownAPIDump.from_dict(dump_dict)# UnknownAPIDump(endpoint='some_api_endpoint', data={'foo': 1, 'bar': '2'}, unknown_things={'undefined_field_name': [1, 2, 3]})dump.to_dict()# {'endpoint': 'some_api_endpoint', 'data': {'foo': 1, 'bar': '2'}, 'undefined_field_name': [1, 2, 3]}Notes:When usingUndefined.INCLUDE, anUndefinedParameterErrorwill be raised if you don't specify
exactly one field of typeCatchAll.Note thatLetterCasedoes not affect values written into theCatchAllfield, they will be as they are given.When specifying a default (or a default factory) for the theCatchAll-field, e.g.unknown_things: CatchAll = None, the default value will be used instead of an empty dict if there are no undefined parameters.Callinginitwith non-keyword arguments resolves the arguments to the defined fields and writes everything else into the catch-all field.All 3 options work as well usingschema().loadsandschema().dumps, as long as you don't overwrite it by specifyingschema(unknown=<a marshmallow value>).
marshmallow uses the same 3 keywords'include', 'exclude', 'raise'.All 3 operations work as well using__init__, e.g.UnknownAPIDump(**dump_dict)willnotraise aTypeError, but write all unknown values to the field tagged asCatchAll.
Classes tagged withEXCLUDEwill also simply ignore unknown parameters. Note that classes tagged asRAISEstill raise aTypeError, andnotaUndefinedParameterErrorif supplied with unknown keywords.Override the default encode / decode / marshmallow field of a specific field?SeeOverridingHandle recursive dataclasses?Object hierarchies where fields are of the type that they are declared within require a small
type hinting trick to declare the forward reference.fromtypingimportOptionalfromdataclassesimportdataclassfromdataclasses_jsonimportdataclass_json@dataclass_json@dataclassclassTree():value:strleft:Optional['Tree']right:Optional['Tree']Avoid usingfrom__future__importannotationsas it will cause problems with the way dataclasses_json accesses the type annotations.Use numpy or pandas types?Data types specific to libraries commonly used in data analysis and machine learning likenumpyandpandasare not supported by default, but you can easily enable them by using custom decoders and encoders. Below are two examples fornumpyandpandastypes.fromdataclassesimportfield,dataclassfromdataclasses_jsonimportconfig,dataclass_jsonimportnumpyasnpimportpandasaspd@dataclass_json@dataclassclassDataWithNumpy:my_int:np.int64=field(metadata=config(decoder=np.int64))my_float:np.float64=field(metadata=config(decoder=np.float64))my_array:np.ndarray=field(metadata=config(decoder=np.asarray))DataWithNumpy.from_json("{\"my_int\": 42,\"my_float\": 13.37,\"my_array\": [1,2,3]}")@dataclass_json@dataclassclassDataWithPandas:my_df:pd.DataFrame=field(metadata=config(decoder=pd.DataFrame.from_records,encoder=lambdax:x.to_dict(orient="records")))data=DataWithPandas.from_dict({"my_df":[{"col1":1,"col2":2},{"col1":3,"col2":4}]})# my_df results in:# col1  col2# 1    2# 3    4data.to_dict()# {"my_df": [{"col1": 1, "col2": 2}, {"col1": 3, "col2": 4}]}Marshmallow 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.fromdataclassesimportdataclassfromdataclasses_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()Briefly, 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)Overriding / ExtendingOverridingFor example, you might want to encode/decodedatetimeobjects using ISO format
rather than the defaulttimestamp.fromdataclassesimportdataclass,fieldfromdataclasses_jsonimportdataclass_json,configfromdatetimeimportdatetimefrommarshmallowimportfields@dataclass_json@dataclassclassDataClassWithIsoDatetime:created_at:datetime=field(metadata=config(encoder=datetime.isoformat,decoder=datetime.fromisoformat,mm_field=fields.DateTime(format='iso')))ExtendingSimilarly, you might want to extenddataclasses_jsonto encodedateobjects.fromdataclassesimportdataclass,fieldfromdataclasses_jsonimportdataclass_json,configfromdatetimeimportdatefrommarshmallowimportfieldsdataclasses_json.cfg.global_config.encoders[date]=date.isoformatdataclasses_json.cfg.global_config.decoders[date]=date.fromisoformat@dataclass_json@dataclassclassDataClassWithIsoDatetime:created_at:datemodified_at:dateaccessed_at:dateAs 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!What if I have other dataclass field extensions that rely onmetadataAll thedataclasses_json.configdoes is return a mapping, namespaced under the key'dataclasses_json'.Say there's another module,other_dataclass_packagethat uses metadata. Here's how you solve your problem:metadata={'other_dataclass_package':'some metadata...'}# pre-existing metadata for another dataclass packagedataclass_json_config=config(encoder=datetime.isoformat,decoder=datetime.fromisoformat,mm_field=fields.DateTime(format='iso'))metadata.update(dataclass_json_config)@dataclass_json@dataclassclassDataClassWithIsoDatetime:created_at:datetime=field(metadata=metadata)You can also manually specify the dataclass_json configuration mapping.@dataclass_json@dataclassclassDataClassWithIsoDatetime:created_at:date=field(metadata={'dataclasses_json':{'encoder':date.isoformat,'decoder':date.fromisoformat,'mm_field':fields.DateTime(format='iso')}})A larger examplefromdataclassesimportdataclassfromdataclasses_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)==bossPerformanceTake a look atthis issueVersioningNote this library is still pre-1.0.0 (SEMVER).The current convention is:PATCHversion upgrades for bug fixes and minor feature additions.MINORversion upgrades for big API features and breaking changes.Once this library is 1.0.0, it will follow standard SEMVER conventions.Python compatibilityAny version that is not listed in the table below we do not test against, though you might still be able to install the library. For future Python versions, please open an issue and/or a pull request, adding them to the CI suite.Python version rangeCompatible dataclasses-json version3.7.x - 3.12.x0.5.x - 0.6.x>= 3.13.xNo official support (yet)RoadmapCurrently the focus is on investigating and fixing bugs in this library, working
on performance, and finishingthis issue.That said, if you think there's a feature missing / something new needed in the
library, please see the contributing section below.ContributingFirst of all, thank you for being interested in contributing to this library.
I really appreciate you taking the time to work on this project.If you're just interested in getting into the code, a good place to start are
issues tagged as bugs.If introducing a new feature, especially one that modifies the public API,
consider submitting an issue for discussion before a PR. Please also take a look
at existing issues / PRs to see what you're proposing has  already been covered
before / exists.I like to follow the commit conventions documentedhereSetting up your environmentThis project usesPoetryfor dependency and venv management. It is quite simple to get ready for your first commit:Installlatest stable PoetryNavigate to where you cloneddataclasses-jsonRunpoetry installCreate a branch and start writing code!