Encoding/json: Parsing Number as uint64

goversion: 1.8

This is in reference to https://golang.org/pkg/encoding/json/#Number. Both
Float64(), and Int64() methods on Number are useful.

Additionally it would be nice to have:

  • Uint64() for large unsigned 64-bit integers; usecase would be to decode
    64-bit hash values in JSON.
  • Value() (interface{}, error) to decode Number as int64, if it fails, then
    to decode Number as float64; usecase would be to deal with schemaless data
    fields that can be polymorphic in its representation.

Are there any recommendations ?

Given that n is a json.Number,

strconv.ParseUint(n.String(), 10, 64)

gives you a uint64. The second method is just an if clause around Int64/Float64 and doesn’t really buy you much as you need to duplicate essentially the same if as a type switch on the return. If you think you don’t need to do that because you don’t care about the return type you can just leave it as a json.Number, i.e, a string.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.