Convert interface {} to a specific type

I am developing a web service that will receive JSON. Go converts types are too strict.

So, I performed the following function to convert interface{} to bool

 func toBool(i1 interface{}) bool { if i1 == nil { return false } switch i2 := i1.(type) { default: return false case bool: return i2 case string: return i2 == "true" case int: return i2 != 0 case *bool: if i2 == nil { return false } return *i2 case *string: if i2 == nil { return false } return *i2 == "true" case *int: if i2 == nil { return false } return *i2 != 0 } return false } 

I believe the function is still not perfect, and I need functions to convert interface{} to string , int , int64 , etc.

So my question is: is there a library (set of functions) in Go that converts interface{} to certain types

UPDATE

My web service receives JSON. I decode it in map[string]interface{} I have no control over those who code it.

That way, all the values ​​that I get are interface{} , and I need a way to cast them in certain types.

So it could be nil , int , float64 , string , [...] , {...} and I want to pass it to what it should be. for example int , float64 , string , []string , map[string]string with processing of all possible cases, including nil , invalid values, etc.

UPDATE2

I get {"s": "wow", "x":123,"y":true} , {"s": 123, "x":"123","y":"true"} , {a:["a123", "a234"]} , {}

 var m1 map[string]interface{} json.Unmarshal(b, &m1) s := toString(m1["s"]) x := toInt(m1["x"]) y := toBool(m1["y"]) arr := toStringArray(m1["a"]) 
+6
source share
1 answer

the objx package does exactly what you want, it can work directly with JSON, and will give you default values ​​and other interesting functions:

Objx provides an objx.Map type, which is a map[string]interface{} which provides a powerful Get method (among others) that allows you to quickly and easily access data on a map, without worrying too much about type statements, missing data, values by default, etc.

This is a small usage example:

 o := objx.New(m1) s := o.Get("m1").Str() x := o.Get("x").Int() y := o.Get("y").Bool() arr := objx.New(m1["a"]) 

Example from a document working with JSON:

 // use MustFromJSON to make an objx.Map from some JSON m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`) // get the details name := m.Get("name").Str() age := m.Get("age").Int() // get their nickname (or use their name if they // don't have one) nickname := m.Get("nickname").Str(name) 

Obviously, you can use something like this with simple runtime:

 switch record[field].(type) { case int: value = record[field].(int) case float64: value = record[field].(float64) case string: value = record[field].(string) } 

But if you check objx accessors , you will see complex code similar to this, but with many use cases, so I think the best solution is to use the objx library.

+6
source

All Articles