Skip to content

Instantly share code, notes, and snippets.

@elmer
Forked from lachlan-eagling/unmarshal_user.go
Created October 26, 2019 12:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elmer/e472a61d0327ca5cd458b4d63198d369 to your computer and use it in GitHub Desktop.
Save elmer/e472a61d0327ca5cd458b4d63198d369 to your computer and use it in GitHub Desktop.
Blog - Anatomy of a Struct (Unmarshaling)
package main
import (
"encoding/json"
"fmt"
)
type User struct {
FirstName string `json:"firstName"`
LastName string `json:"surname"`
Username string `json:"username"`
Age int `json:"age"`
}
func main() {
var user User
userJson := []byte(`{"firstName": "Lachlan", "surname": "Eagling", "username": "Lachlan_E", "age": 28}`)
if err := json.Unmarshal(userJson, &user); err != nil {
fmt.Println(err)
}
fmt.Printf("FirstName: %s | LastName: %s | Username: %s, | Age: %d", user.FirstName, user.LastName, user.Username, user.Age)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment