I'm new to golang and I'd like to get a json object into my code:
func getUserRandking() []KVU {
url := "http://127.0.0.1:8080/users"
spaceClient := http.Client{ Timeout: time.Second * 10,
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatal(err)
}
req.Header.Set("User-Agent", "spacecount-tutorial")
res, getErr := spaceClient.Do(req)
if getErr != nil {
log.Fatal(getErr)
}
body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
log.Fatal(readErr)
}
var users1 []KVU
jsonErr := json.Unmarshal(body, &users1)
if jsonErr != nil {
log.Fatal(jsonErr)
}
fmt.Println(users1)
return users1
}
but I get this runtime error
json: cannot unmarshal string into Go value of type []main.KVU exit status 1
The json that I'm trying to import is like this:
{
"name": "userslist",
"children": [
{
"name": "cat",
"value": 1,
"url": "http://example.com/1.jpg"
},
{
"name": "dog",
"value": 2,
"url": "http://example.com/2.jpg"
}
]
}
I have tried different type definitions like Users
below:
type KVU struct {
Key string `json:"name"`
Value int `json:"value"`
Url string `json:"url"`
}
type Users struct {
Name string `json:"name"`
Children []KVU `json:"children"`
}
But that also leads to:
json: cannot unmarshal string into Go value of type []main.Users
How can I fix this?