Error "cannot convert data (type interface{}) to type string: need type assertion" in Go
Hello everyone! I just started learning Go and encountered an unclear error. I'm writing a simple program that receives data from JSON and tries to use it.
Here is my code:
```go
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonString := `{"name": "John", "age": 30}`
var data interface{}
json.Unmarshal([]byte(jsonString), &data)
name := data["name"] // Error: cannot convert data (type interface {}) to type string: need type assertion
fmt.Println(name)
}
```
I expected that `data["name"]` would return the string "John", but the compiler gives an error: "cannot convert data (type interface {}) to type string: need type assertion". I understand that `data` is of type `interface{}`, but how do I get the string value? I tried writing `data.(ma
No answers yet.
Log in to leave an answer
Blogs