Skip to content

Instantly share code, notes, and snippets.

@niorad
Last active September 16, 2017 12:21
Show Gist options
  • Save niorad/1132dfddc449b98361eb50c3dfc07365 to your computer and use it in GitHub Desktop.
Save niorad/1132dfddc449b98361eb50c3dfc07365 to your computer and use it in GitHub Desktop.
Simple JSON-to-Struct-Example in Golang
package main
import (
"encoding/json"
"fmt"
)
type Fleet struct {
Cars []Car
Countries []string
}
type Car struct {
Model string
Serial string
PS float64
}
var exampleJSON = []byte(`
{
"cars":[
{
"model":"A3",
"serial":"xx6665",
"ps":514
},
{
"model":"X",
"serial":"ab4321",
"ps":320
}
],
"countries":[
"DE",
"AT",
"ES",
"CZ",
"HR"
]
}`)
func main() {
var myFleet Fleet
err := json.Unmarshal(exampleJSON, &myFleet)
if err != nil {
panic(err)
}
fmt.Println(myFleet)
fmt.Println(myFleet.Cars[0].Model)
fmt.Println(myFleet.Cars[1].PS)
fmt.Println(myFleet.Cars[0].Serial)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment