Skip to content

Instantly share code, notes, and snippets.

@kjk
Created November 5, 2019 09:08
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 kjk/9abfbfbd4c8739650632521fd3c337ea to your computer and use it in GitHub Desktop.
Save kjk/9abfbfbd4c8739650632521fd3c337ea to your computer and use it in GitHub Desktop.
Parse JSON into a struct
// :collection Essential Go
package main
import (
"encoding/json"
"fmt"
"log"
)
// :show start
type Person struct {
Name *string `json:"name"`
Age int `json:"age"`
City string
Occupation string
}
var jsonStr = `{
"name": "Jane",
"age": 24,
"city": "ny"
}`
// :show end
func main() {
// :show start
var p Person
err := json.Unmarshal([]byte(jsonStr), &p)
if err != nil {
log.Fatalf("json.Unmarshal failed with '%s'\n", err)
}
fmt.Printf("Person struct parsed from JSON: %#v\n", p)
fmt.Printf("Name: %#v\n", *p.Name)
// :show end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment