You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If dataclasses have optional fields, JSON generated by the dump is polluted by nulls. This makes it verbose and confuses legacy servers.
This is less of an issue with classic Marshmallow, since not required fields will simply be omitted from the dictionary, and will not generate nulls in the output. It is possible to squash nulls by using a custom base schema with a post-dump hook, but I believe we need an easier way.
We need a way to get rid of "state": null. The solution that I found involves defining a custom base schema:
class AvoidNullsSchema(marshmallow.Schema):
@marshmallow.post_dump(pass_many=False)
def postdump(self, data, **kwargs):
keys = list(data.keys())
for key in keys:
if data[key] is None:
del data[key]
return data
schema = class_schema(Location, AvoidNullsSchema)
location = schema.loads(json_str)
round_trip_json = schema.dumps(location) # '{"city": "Paris", "country": "France"}', no null state
This is good, but it is too hard on a regular library user to implement custom post-dump hook every time they need to get rid of nulls. We need a built-in option for that, something along the lines of:
If dataclasses have optional fields, JSON generated by the dump is polluted by
null
s. This makes it verbose and confuses legacy servers.This is less of an issue with classic Marshmallow, since not required fields will simply be omitted from the dictionary, and will not generate nulls in the output. It is possible to squash nulls by using a custom base schema with a post-dump hook, but I believe we need an easier way.
Example:
We need a way to get rid of
"state": null
. The solution that I found involves defining a custom base schema:This is good, but it is too hard on a regular library user to implement custom post-dump hook every time they need to get rid of nulls. We need a built-in option for that, something along the lines of:
I am ready to provide a pull request if you are OK with the idea.
The text was updated successfully, but these errors were encountered: