Skip to content

Instantly share code, notes, and snippets.

@eyeezzi
Last active January 3, 2018 03:53
Show Gist options
  • Save eyeezzi/63bcfd91f67797b4e433d1cc9f282330 to your computer and use it in GitHub Desktop.
Save eyeezzi/63bcfd91f67797b4e433d1cc9f282330 to your computer and use it in GitHub Desktop.
How to read JSON data that matches a struct in Go.
package main
import (
"encoding/json"
"fmt"
)
type User struct {
Fname string
Lname string
Age int
}
func main() {
// Go stores JSON data as an array of bytes.
jstr := `{"fname":"john","lname":"doe","age":25}`
b := []byte(jstr)
// If the incoming JSON data *matches* our struct, Go can directly
// decode the JSON to our struct.
// See https://blog.golang.org/json-and-go for the matching rules.
var u User
// Unmarshalling => decoding JSON to Go object.
if err := json.Unmarshal(b, &u); err != nil {
fmt.Println(err.Error())
}
fmt.Println(u.Fname)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment