
{"id":5127,"date":"2024-10-04T13:59:25","date_gmt":"2024-10-04T17:59:25","guid":{"rendered":"https:\/\/ikriv.com\/blog\/?p=5127"},"modified":"2024-10-04T13:59:25","modified_gmt":"2024-10-04T17:59:25","slug":"marshmallow-dataclass-eliminating-nulls-in-the-resulting-json","status":"publish","type":"post","link":"https:\/\/ikriv.com\/blog\/?p=5127","title":{"rendered":"Marshmallow-dataclass: eliminating nulls in the resulting JSON"},"content":{"rendered":"<p>When serializing a dataclass, by default <code>marshmallow-dataclass<\/code> emits nulls for all fields that have the value of <code>None<\/code>. This is not necessariy most of the time and pollutes the resulting JSON.<\/p>\n<p>There seems to be no easy way to <i>prevent<\/i> generating the nulls, but we can remove them after the fact by creating a special base schema with a <code>post_dump<\/code> hook.<\/p>\n<p>Example:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom typing import Optional\r\nfrom dataclasses import dataclass\r\nfrom marshmallow import Schema, post_dump\r\nfrom marshmallow_dataclass import class_schema\r\n\r\nclass RemoveNullsSchema(Schema):\r\n    # remove None values from the generated dictionary, which eliminates nulls in the final JSON\r\n    @post_dump(pass_many=False)\r\n    def postdump(self, data, **kwargs):\r\n        for key in list(data.keys()):\r\n            if data&#x5B;key] is None:\r\n                del data&#x5B;key]\r\n        return data\r\n\r\n@dataclass\r\nclass Point:\r\n    x: float\r\n    y: float\r\n    name: Optional&#x5B;str] = None\r\n    \r\np = Point(2,3)\r\nregular_schema = class_schema(Point)()\r\nprint(regular_schema.dumps(p))  # {&quot;x&quot;: 2.0, &quot;y&quot;: 3.0, &quot;name&quot;: null}  \r\n\r\nenhanced_schema = class_schema(Point, RemoveNullsSchema)()\r\nprint(enhanced_schema.dumps(p)) # {&quot;x&quot;: 2.0, &quot;y&quot;: 3.0}  \r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>When serializing a dataclass, by default marshmallow-dataclass emits nulls for all fields that have the value of None. This is not necessariy most of the time and pollutes the resulting <a href=\"https:\/\/ikriv.com\/blog\/?p=5127\" class=\"more-link\">[&hellip;]<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"Layout":"","footnotes":""},"categories":[26],"tags":[],"class_list":["entry","author-ikriv","post-5127","post","type-post","status-publish","format-standard","category-python"],"_links":{"self":[{"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5127","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=5127"}],"version-history":[{"count":1,"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5127\/revisions"}],"predecessor-version":[{"id":5128,"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5127\/revisions\/5128"}],"wp:attachment":[{"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=5127"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=5127"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=5127"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}