Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
convert json to native Go
// take an interface{} string and turn it into a real string
func To_S(i interface{}) (string,error) {
i_str,ok := i.(string)
if !ok {
e := fmt.Sprintf("cannot convert %v to string\n",i)
return "", errors.New(e)
}
return i_str,nil
}
// take an interface{} string and turn it into a real string
func To_N(i interface{}) (int64,error) {
i_int64,ok := i.(int64)
if !ok {
e := fmt.Sprintf("cannot convert %v to int64\n",i)
return 0, errors.New(e)
}
return i_int64,nil
}
// take an interface{} string and turn it into a list of real strings.
// also return a list of error elements if there were any
func To_SS(i interface{}) ([]string,[]string,error) {
i_int,ok := i.([]interface {})
if !ok {
e := fmt.Sprintf("cannot convert %v to []interface {}\n",i)
return nil,nil, errors.New(e)
}
var i_str_list []string
var error_list []string
for _,v := range i_int {
i_str,ok := v.(string)
if ok {
i_str_list = append(i_str_list,i_str)
} else {
e_str := fmt.Sprint("%v",v)
error_list = append(error_list,string(e_str))
}
}
if len(error_list) > 0 {
return i_str_list,error_list,errors.New("some conversion errs")
}
return i_str_list,error_list,nil
}
// take an interface{} int64 and turn it into a list of real int64s.
// also return a list of error elements if there were any
func To_NS(i interface{}) ([]int64,[]string,error) {
i_int,ok := i.([]interface {})
if !ok {
e := fmt.Sprintf("cannot convert %v to []interface {}\n",i)
return nil,nil, errors.New(e)
}
var i_int64_list []int64
var error_list []string
for _,v := range i_int {
i_int64,ok := v.(int64)
if ok {
i_int64_list = append(i_int64_list,i_int64)
} else {
e_str := fmt.Sprint("%v",v)
error_list = append(error_list,string(e_str))
}
}
if len(error_list) > 0 {
return i_int64_list,error_list,errors.New("some conversion errs")
}
return i_int64_list,error_list,nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment