Last active
September 16, 2017 12:21
-
-
Save niorad/1132dfddc449b98361eb50c3dfc07365 to your computer and use it in GitHub Desktop.
Simple JSON-to-Struct-Example in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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