Skip to content

Need an easy way to avoid nulls in generated JSON #276

@ikriv

Description

@ikriv

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.

Example:

json_str = '{"city": "Paris", "country": "France"}'

@dataclass
class Location:
   city: str
   country: str
   state: Optional[str] = None

schema = class_schema(Location)
location = schema.loads(json_str)
round_trip_json = schema.dumps(location) # '{"city": "Paris", "country": "France", "state": null}'

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:

schema = class_schema(Location, skip_none_on_dump = True)
location = schema.loads(json_str)
round_trip_json = schema.dumps(location) 

I am ready to provide a pull request if you are OK with the idea.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions