From 8b0346e1f77b976ec736ca85935276a49b9d630e Mon Sep 17 00:00:00 2001 From: "kevin.lin" Date: Tue, 30 Nov 2021 15:44:07 +0800 Subject: [PATCH] Add support for parsing json.Number to uint64 --- mapstructure.go | 8 ++------ mapstructure_test.go | 6 ++++++ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/mapstructure.go b/mapstructure.go index dcee0f2d..6b81b006 100644 --- a/mapstructure.go +++ b/mapstructure.go @@ -684,16 +684,12 @@ func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) e } case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": jn := data.(json.Number) - i, err := jn.Int64() + i, err := strconv.ParseUint(string(jn), 0, 64) if err != nil { return fmt.Errorf( "error decoding json.Number into %s: %s", name, err) } - if i < 0 && !d.config.WeaklyTypedInput { - return fmt.Errorf("cannot parse '%s', %d overflows uint", - name, i) - } - val.SetUint(uint64(i)) + val.SetUint(i) default: return fmt.Errorf( "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", diff --git a/mapstructure_test.go b/mapstructure_test.go index 04549b47..8abe2342 100644 --- a/mapstructure_test.go +++ b/mapstructure_test.go @@ -24,6 +24,7 @@ type Basic struct { Vdata interface{} VjsonInt int VjsonUint uint + VjsonUint64 uint64 VjsonFloat float64 VjsonNumber json.Number } @@ -224,6 +225,7 @@ func TestBasicTypes(t *testing.T) { "vdata": 42, "vjsonInt": json.Number("1234"), "vjsonUint": json.Number("1234"), + "vjsonUint64": json.Number("9223372036854775809"), // 2^63 + 1 "vjsonFloat": json.Number("1234.5"), "vjsonNumber": json.Number("1234.5"), } @@ -287,6 +289,10 @@ func TestBasicTypes(t *testing.T) { t.Errorf("vjsonuint value should be 1234: %#v", result.VjsonUint) } + if result.VjsonUint64 != 9223372036854775809 { + t.Errorf("vjsonuint64 value should be 9223372036854775809: %#v", result.VjsonUint64) + } + if result.VjsonFloat != 1234.5 { t.Errorf("vjsonfloat value should be 1234.5: %#v", result.VjsonFloat) }