Created
November 5, 2019 09:08
-
-
Save kjk/9abfbfbd4c8739650632521fd3c337ea to your computer and use it in GitHub Desktop.
Parse JSON into a struct
This file contains 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
// :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