I can't seem to be able to parse a json file in Go. I've tried a bunch of tutorials, but I can't see what I'm doing wrong. The JSON looks like this.
{
"latitude": 34.4048358,
"longitude": -119.5313565,
"dateTime": "Thu Jun 26 2014 08:36:42 GMT-0700 (PDT)"
}
And my main file looks like this.
package main
import (
"encoding/json"
"fmt"
)
type Position struct {
latitude float64 `json:latitude`
longitude float64 `json:logitude`
dateTime string `json:dateTime`
}
func jsonToPosition(jsonData []byte) {
position := &Position{}
if err := json.Unmarshal(jsonData, position); err != nil {
fmt.Println(err)
}
fmt.Println(position)
}
func main() {
jsonToPosition([]byte(`{"latitude":34.4048358,"longitude":-119.5313565,"dateTime":"Thu Jun 26 2014 08:36:42 GMT-0700 (PDT)"}`))
}
I don't get an error or anything. I just get &{0 0 }
when I do fmt.Println(position)
.
This is a common mistake: you did not export values in the Position
structure, so the json
package was not able to use it. Use a capital letter in the variable name to do so:
type Position struct {
Latitude float64 `json:latitude`
Longitude float64 `json:logitude`
DateTime string `json:dateTime`
}