lidatong/dataclasses-json

[FEATURE] Omitting undefined Optional field when serializing

Opened this issue · 2 comments

Description

When using a class with an optional field, for which no value has been defined (i.e. is None) I would like the generated serialized json not to contain that field.

When the output must validate against a predefined json shema, serializing the filed with a null of default value makes the validation fails.

Maybe this behavior is already supported but I couldn't find any way to achieve this.

See this example for is currently generated and what I would like to have instead :

from dataclasses import dataclass
from typing import Optional
from dataclasses_json import DataClassJsonMixin

@dataclass
class Foo(DataClassJsonMixin):
    bar: str
    foo: Optional[str] = None

f = Foo(bar="b")

# here we get  {"bar": "b", "foo": null}
# as foo is optional and not used here, I would like to get {"bar": "b"}
# This would also validate a json schema where 'foo' is not defined as "required"
print(f" json str : {f.to_json()}")

Possible solution

No response

Alternatives

Currently I use an empty string as a default value, It is the only way I've found to valide the schema, but unfortunately it is not really correct as a property with an empty string as a value is not equivalent to not having the property at all.

Context

No response

@george-zubrienko, could be a good addition for v1

Yeah I agree. Re v1, it has not been forgotten, I have one major contrib I need to make within other OSS project and then I will have time to kick of the ball on v1. High hopes for Feb next year. Also considering how many projects depend on DCJ, I see no harm in taking things slow :D