Quick actions

cmd+k|ctrl+k

Navigation

Languages

JSON / Go to JSON type mappings / Essential Go

Snippet info

Language

Go

Visibility

public

Author

kkowalczyk

Created

2019-03-26T09:43:08Z

Updated

2019-03-26T09:43:08Z

package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"os"
	"text/tabwriter"
)

func printSerialized(v interface{}, w io.Writer) {
	d, err := json.Marshal(v)
	if err != nil {
		log.Fatalf("json.Marshal failed with '%s'\n", err)
	}
	fmt.Fprintf(w, "%T\t%s\n", v, string(d))
}

func main() {
	w := new(tabwriter.Writer)
	w.Init(os.Stdout, 5, 0, 1, ' ', 0)
	fmt.Fprint(w, "Go type:\tJSON value:\n")
	fmt.Fprint(w, "\t\n")
	printSerialized(nil, w)
	printSerialized(5, w)
	printSerialized(8.23, w)
	printSerialized("john", w)
	ai := []int{5, 4, 18}
	printSerialized(ai, w)
	a := []interface{}{4, "string"}
	printSerialized(a, w)
	d := map[string]interface{}{
		"i": 5,
		"s": "foo",
	}
	printSerialized(d, w)
	s := struct {
		Name string
		Age  int
	}{
		Name: "John",
		Age:  37,
	}
	printSerialized(s, w)
	w.Flush()
}
INFO