Skip to content

Instantly share code, notes, and snippets.

@kjk
Created November 5, 2019 09:07
Show Gist options
  • Select an option

  • Save kjk/b0ce5c49fb5e692a0daf62bcbb558f98 to your computer and use it in GitHub Desktop.

Select an option

Save kjk/b0ce5c49fb5e692a0daf62bcbb558f98 to your computer and use it in GitHub Desktop.
Serialize struct as JSON
// 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