Created
November 5, 2019 09:07
-
-
Save kjk/b0ce5c49fb5e692a0daf62bcbb558f98 to your computer and use it in GitHub Desktop.
Serialize struct as JSON
This file contains hidden or 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 { | |
| fullName string | |
| Name string | |
| Age int `json:"age"` | |
| City string `json:"city"` | |
| } | |
| // :show end | |
| func main() { | |
| // :show start | |
| p := Person{ | |
| Name: "John", | |
| Age: 37, | |
| City: "SF", | |
| } | |
| d, err := json.Marshal(&p) | |
| if err != nil { | |
| log.Fatalf("json.MarshalIndent failed with '%s'\n", err) | |
| } | |
| fmt.Printf("Person in compact JSON: %s\n", string(d)) | |
| d, err = json.MarshalIndent(p, "", " ") | |
| if err != nil { | |
| log.Fatalf("json.MarshalIndent failed with '%s'\n", err) | |
| } | |
| fmt.Printf("Person in pretty-printed JSON:\n%s\n", string(d)) | |
| // :show end | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment