Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert interface{} to certain type

Tags:

casting

go

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

So I did following function to convert interface{} in 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 that function is still not perfect and I need functions to convert interface{} in string, int, int64, etc

So my question: Is there library (set of functions) in Go that will convert interface{} to certain types

UPDATE

My web service receive JSON. I decode it in map[string]interface{} I do not have control on those who encode it.

So all values I receive are interface{} and I need way to cast it in certain types.

So it could be nil, int, float64, string, [...], {...} and I wish to cast it to what it should be. e.g. int, float64, string, []string, map[string]string with handling of all possible cases including nil, wrong values, etc

UPDATE2

I receive {"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"])
like image 269
Shuriken Avatar asked Jan 18 '14 18:01

Shuriken


2 Answers

I came here trying to convert from interface{} to bool and Reflect gave me a clean way to do it:

Having:

v := interface{}
v = true

The solution 1:

if value, ok := v.(bool); ok {
  //you can use variable `value`
}

The solution 2:

reflect.ValueOf(v).Bool()

Then reflect offers a function for the Type you need.

like image 193
Oscar Gallardo Avatar answered Oct 09 '22 10:10

Oscar Gallardo


Fast/Best way is 'Cast' in time execution (if you know the object):

E.g.

package main    
import "fmt"    
func main() {
    var inter (interface{})
    inter = "hello"
    var value string
    value = inter.(string)
    fmt.Println(value)
}

Try here

like image 39
Darlan D. Avatar answered Oct 09 '22 09:10

Darlan D.