H
H
helixly2017-11-03 19:08:49
go
helixly, 2017-11-03 19:08:49

How to correctly convert types to int obtained from JSON?

It doesn't sound complicated, but in GO all numbers obtained from json.Unmarshal are of type float64.
What if I need to receive an int and write some kind of helper for this. To get directly from the "method" the value of the sent data in the request in the required format?
I climb into the encode / json documentation, I find the UseNumber () decoder method, which converts all numbers instead of float64 to the json.Number type, which in turn has several methods for converting to other types, but the types are again not the ones that are needed, only int64, Float64,string

func (c *Controller) GetInt(name string) (i int) {
  if val, status := c.Params[name]; status {
    switch val.(type) {
    case json.Number:
      i64, _ := val.(json.Number).Int64()
      i = int(i64)
    }
  }
  return
}

It turns out this is the code, I had to add a switch construction to eliminate panic if a string suddenly arrives in json instead of a number. The function works, but it's kind of complicated, no? Any thoughts on how to simplify?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
evnuh, 2017-11-03
@evnuh

var s struct {
  I int
}
json.Unmarshal([]byte(`{"I": 5}`), &s)
fmt.Println(s.I) // 5

works great.
You can also cast int64 to int with int()
var i64 int64 = 5
var i int = int(i64)
fmt.Println(i)	// 5

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question