This question already has an answer here:
So basically, I'm trying to parse a JSON and assign its values to a struct. I get no errors when I run this, but the returned struct yeilds {0 0 0} which is incorrect. I tried putting in a fake url to see if there was just a connection issue, but that doesn't seem to be the case.
Since Go isn't asynchronous, there shouldn't be a problem with just calling things sequentially, right?
Here's the JSON I hosted on some site
{"ability":5335,"time":338,"level":1}
Here's the code
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type prog struct {
ability int64
time int64
level int64
}
func main() {
url := "https://api.myjson.com/bins/2c54h"
//get the data from the url
res, err := http.Get(url)
//error handling
defer res.Body.Close()
if err != nil {
panic(err)
}
// read json response
data, err := ioutil.ReadAll(res.Body)
// error handling
var jsonData prog
err = json.Unmarshal([]byte(data), &jsonData)
if err != nil {
panic(err)
}
//test struct data
fmt.Println(jsonData)
}
The JSON is here
</div>
Rename the fields of your struct so that they start with capital letters, and it should work.
If necessary, also append a hint at the end of each field name, using backticks.
The fields in your struct must be exported (start with a capital letter) for the JSON package to be able to see them.
type prog struct {
Ability int64
Time int64
Level int64
}
See http://play.golang.org/p/yjtth5kliB for an example.
The fact you're downloading the data before the JSON parsing is unrelated to what you're seeing.
You almost had it. You just need to change the way you declare your struct to include capital letters (otherwise they won't be exported) and specify that the json
uses lowercase names.
type prog struct {
Ability int64 `json:"ability"`
Time int64 `json:"time"`
Level int64 `json:"level"`
}