You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In the current api we cannot check if the field is present. As {} and {"foo":null} will result with Valid: false and nil value. However we can do this:
diff --git a/gonull.go b/gonull.go
index b20a29e..deab37d 100644
--- a/gonull.go+++ b/gonull.go@@ -19,8 +19,9 @@ var (
// It keeps track of the value (Val) and a flag (Valid) indicating whether the value has been set.
// This allows for better handling of nullable values, ensuring proper value management and serialization.
type Nullable[T any] struct {
- Val T- Valid bool+ Val T+ Valid bool+ Present bool
}
// NewNullable creates a new Nullable with the given value and sets Valid to true.
@@ -59,6 +60,7 @@ func (n Nullable[T]) Value() (driver.Value, error) {
// UnmarshalJSON implements the json.Unmarshaler interface for Nullable, allowing it to be used as a nullable field in JSON operations.
// This method ensures proper unmarshalling of JSON data into the Nullable value, correctly setting the Valid flag based on the JSON data.
func (n *Nullable[T]) UnmarshalJSON(data []byte) error {
+ n.Present = true
if string(data) == "null" {
n.Valid = false
return nil
Hey @zekth, thanks for pointing out this issue. It's a good topic to discuss. frankly, I'm not sure when you'd need to use Foo gonull.Nullable[*string] 'json:"foo"', but as you said, it might be a rare but useful case. Freel free to open PR, I'll gladly check and approve it!
Thank you!
This is an annoying JSON x Golang edge case but found a solution for this
Let's assume we have a struct like so:
we want to be able to handle those cases:
{"foo":"f"}
{}
{"foo": null}
In the current api we cannot check if the field is present. As
{}
and{"foo":null}
will result withValid: false
andnil
value. However we can do this:Then we have this successful test:
Happy to raise a PR if the implementation is ok.
The text was updated successfully, but these errors were encountered: