Skip to content

Instantly share code, notes, and snippets.

@davewalk
Created April 4, 2016 16:27
Show Gist options
  • Save davewalk/47cfa17ed717c83d4a1c1109e03016ad to your computer and use it in GitHub Desktop.
Save davewalk/47cfa17ed717c83d4a1c1109e03016ad to your computer and use it in GitHub Desktop.
Go empty interface value that is actually of type []string to a comma-separated string
package main
import (
"encoding/json"
"fmt"
"reflect"
"strings"
)
type Product struct {
OutProduct map[string]interface{} `json:"out_product"`
}
func main() {
raw := []byte(`{"out_product": {"test": ["hello", "hi"]}}`)
p := Product{}
_ = json.Unmarshal(raw, &p)
switch val := p.OutProduct["test"].(type) {
case interface{}:
v := reflect.ValueOf(val)
if v.Kind() != reflect.Slice {
fmt.Println("not a slice")
return
}
n := make([]string, v.Len())
for i := 0; i < v.Len(); i++ {
switch val := v.Index(i).Interface().(type) {
case string:
n[i] = val
default:
break
}
}
result := strings.Join(n, ", ")
fmt.Printf("result is: %v", result)
default:
fmt.Println("not an interface{}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment