Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ikriv opened this issue Jul 26, 2024 · 0 comments
Open

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

ikriv opened this issue Jul 26, 2024 · 0 comments

Comments

@ikriv
Copy link

ikriv commented Jul 26, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant