Skip to content
This repository has been archived by the owner on Jul 22, 2024. It is now read-only.

Commit

Permalink
Merge pull request #261 from onlyice/feature/json-number-to-uint64
Browse files Browse the repository at this point in the history
Add support for parsing json.Number to uint64
  • Loading branch information
mitchellh authored Dec 1, 2021
2 parents 5ac1f6a + ea0720b commit f41e93f
Show file tree
Hide file tree
Showing 2 changed files with 10 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
8 changes: 8 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 Expand Up @@ -1721,6 +1727,7 @@ func TestDecodeTable(t *testing.T) {
"Vdata": []byte("data"),
"VjsonInt": 0,
"VjsonUint": uint(0),
"VjsonUint64": uint64(0),
"VjsonFloat": 0.0,
"VjsonNumber": json.Number(""),
},
Expand Down Expand Up @@ -1762,6 +1769,7 @@ func TestDecodeTable(t *testing.T) {
"Vdata": []byte("data"),
"VjsonInt": 0,
"VjsonUint": uint(0),
"VjsonUint64": uint64(0),
"VjsonFloat": 0.0,
"VjsonNumber": json.Number(""),
},
Expand Down

0 comments on commit f41e93f

Please sign in to comment.