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

[FEATURE] Omitting undefined Optional field when serializing #501

Open
PierreRust opened this issue Nov 16, 2023 · 2 comments
Open

[FEATURE] Omitting undefined Optional field when serializing #501

PierreRust opened this issue Nov 16, 2023 · 2 comments
Assignees
Labels
api/v1 enhancement New feature or request

Comments

@PierreRust
Copy link

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

@PierreRust PierreRust added the enhancement New feature or request label Nov 16, 2023
@USSX-Hares
Copy link
Collaborator

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

@george-zubrienko
Copy link
Collaborator

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api/v1 enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants