Omitting fields when serializing
See original GitHub issueIs it possible to omit fields when to_dict
or to_json
is invoked? My use-case is I have fields with sensitive information that I only want available to the internal parts of my application, and would like to ensure they’re never pushed to my end-users.
Right now, I’m accomplishing it by overriding to_dict
as follows:
@dataclass
class MyObject(DataClassJsonMixin):
"""An object."""
id_: uuid.UUID = field(metadata=config(field_name="id"))
name: str
secret: str
another_secret: str
def to_dict( # type: ignore[override]
self, omit_sensitive=True, **kwargs
) -> Dict[str, "dataclasses_json.core.Json"]:
"""Serialize the dataclass, with an optional ability to omit sensitive/internal fields."""
serialized = super().to_dict(**kwargs)
if omit_sensitive:
for field_name in list(serialized.keys()):
if field_name in ("secret", "another_secret"):
del serialized[field_name]
return serialized
Ideally, this would be something I could define as part of the field()
. Is this currently possible with dataclass-json, and, if not, would this be something that you would consider for future functionality?
Issue Analytics
- State:
- Created 3 years ago
- Reactions:2
- Comments:6 (3 by maintainers)
Top Results From Across the Web
How can we ignore the fields during JSON serialization in ...
If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson...
Read more >Jackson Ignore Properties on Marshalling
This tutorial will show how to ignore certain fields when serializing an object to JSON using Jackson 2.x.
Read more >c# - Omit certain fields for specific Serialization
I have the following line in my .NET Core code : var serializedstuff = Newtonsoft.Json.JsonConvert.SerializeObject(myuserclass);.
Read more >Support ignoring fields when serializing #149 - tophat/syrupy
Successfully merging a pull request may close this issue. fix: support ignoring fields when serializing tophat/syrupy. 4 participants.
Read more >JSON and XML Serialization in ASP.NET Web API
By default, all public properties and fields are included in the serialized JSON. To omit a property or field, decorate it with the...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Thank you @arusahni, this worked perfectly for my use-case. Thank you @lidatong for the great package.
I don’t think dropping everything that has
None
as default is the best solution to this problem. I think a better solution would add something like