Skip to content

Instantly share code, notes, and snippets.

@ariesmcrae
Created October 3, 2018 02:05
Show Gist options
  • Save ariesmcrae/2e099c305a22967b1d8d2b45ca27c4e8 to your computer and use it in GitHub Desktop.
Save ariesmcrae/2e099c305a22967b1d8d2b45ca27c4e8 to your computer and use it in GitHub Desktop.
golang: Unmarshall json to struct
// play.golang.org/p/-fTKnXVctQ0
package main
import (
"encoding/json"
"fmt"
)
type Employee struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
}
/* Unmarshall json to struct */
func main() {
employeeJsonStr := `{
"first_name":"John",
"last_name":"Smith"
}`
employee := unmarshall(employeeJsonStr)
fmt.Println(employee.FirstName) // John
fmt.Println(employee.LastName) // Smith
}
func unmarshall(employeeJsonStr string) Employee {
employee := &Employee{}
json.Unmarshal([]byte(employeeJsonStr), employee)
return *employee
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment