Skip to content

Commit

Permalink
Add support for parsing json.Number to uint64
Browse files Browse the repository at this point in the history
  • Loading branch information
kevin.lin committed Nov 30, 2021
1 parent 5ac1f6a commit 8b0346e
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
8 changes: 2 additions & 6 deletions mapstructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -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'",
Expand Down
6 changes: 6 additions & 0 deletions mapstructure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type Basic struct {
Vdata interface{}
VjsonInt int
VjsonUint uint
VjsonUint64 uint64
VjsonFloat float64
VjsonNumber json.Number
}
Expand Down Expand Up @@ -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"),
}
Expand Down Expand Up @@ -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)
}
Expand Down

0 comments on commit 8b0346e

Please sign in to comment.