json - Golang check if interface type is nil -
when unmarshaling string of json using golang's json.unmarshal() function, unmarshal string map[string]interface{}. i not sure weather there more optimal way of decoding json.
to point, json unmarshal's type nil, not string (or int etc.). throws panic saying "interface conversion: interface nil, not int". how can avoid panic or check if interface's type nil or not?
here example of problem in action: https://play.golang.org/p/0atzxbbdos
check key exist instead of letting panic.
func keyexists(decoded map[string]interface{}, key string) { val, ok := decoded[key] return ok && val != nil } func main() { jsontext := `{ "name": "jimmy", "age": 23 }` var decoded map[string]interface{} if err := json.unmarshal([]byte(jsontext), &decoded); err != nil { fmt.println(err) os.exit(0) } if keyexists(decoded, "name") { fmt.println(decoded["name"].(string)) } if keyexists(decoded, "age") { fmt.println(decoded["age"].(float64)) } if keyexists(decoded, "gender") { fmt.println(decoded["gender"].(int)) } }
also, far being optimal if know json like. specified in documentation, can unmarshal directly struct:
type human struct { name string age int gender int } func main() { jsontext := `{ "name": "jimmy", "age": 23 }` decoded := human{} if err := json.unmarshal([]byte(jsontext), &decoded); err != nil { fmt.println(err) os.exit(0) } fmt.println(decoded.name) fmt.println(decoded.age) fmt.println(decoded.gender) }
Comments
Post a Comment