From 98e22d49b90fcbb66d3665a100d58a443bc7c8e7 Mon Sep 17 00:00:00 2001 From: ik Date: Mon, 6 Jan 2025 13:33:42 +0100 Subject: [PATCH 1/2] Treat empty string as null for Int and Float data types --- internal/float.go | 5 +++++ internal/int.go | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/internal/float.go b/internal/float.go index 167fd62..a991fd6 100644 --- a/internal/float.go +++ b/internal/float.go @@ -22,6 +22,11 @@ func UnmarshalFloatJSON(data []byte, value *float64, valid *bool) error { if err := json.Unmarshal(data, &str); err != nil { return fmt.Errorf("null: couldn't unmarshal number string: %w", err) } + if len(str) == 0 { + *value = 0 + *valid = false + return nil + } n, err := strconv.ParseFloat(str, 64) if err != nil { return fmt.Errorf("null: couldn't convert string to int: %w", err) diff --git a/internal/int.go b/internal/int.go index 5267b58..04c627a 100644 --- a/internal/int.go +++ b/internal/int.go @@ -25,6 +25,11 @@ func UnmarshalIntJSON[T Integer, U int64 | uint64](data []byte, value *T, valid if err := json.Unmarshal(data, &str); err != nil { return fmt.Errorf("null: couldn't unmarshal number string: %w", err) } + if len(str) == 0 { + *value = 0 + *valid = false + return nil + } n, err := parse(str, 10, bits) if err != nil { return fmt.Errorf("null: couldn't convert string to int: %w", err) From a706d2fb3c9857cb1112764ba266639ed0065c1e Mon Sep 17 00:00:00 2001 From: ik Date: Mon, 6 Jan 2025 15:10:36 +0100 Subject: [PATCH 2/2] Treat empty string as null for Int and Float data types - fix tests --- float_test.go | 5 ++--- int_test.go | 5 ++--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/float_test.go b/float_test.go index d4e9ab6..3679818 100644 --- a/float_test.go +++ b/float_test.go @@ -58,9 +58,8 @@ func TestUnmarshalFloat(t *testing.T) { var blank Float err = json.Unmarshal(floatBlankJSON, &blank) - if err == nil { - panic("expected error") - } + maybePanic(err) + assertNullFloat(t, blank, "blank json") var badType Float err = json.Unmarshal(boolJSON, &badType) diff --git a/int_test.go b/int_test.go index 8b0e897..94e9e30 100644 --- a/int_test.go +++ b/int_test.go @@ -82,9 +82,8 @@ func testUnmarshalInt[N nullint](t *testing.T) { var bi N err = json.Unmarshal(floatBlankJSON, &bi) - if err == nil { - panic("err should not be nill") - } + maybePanic(err) + assertNullInt(t, bi, "blank json") var null N err = json.Unmarshal(nullJSON, &null)