Beispiel #1
0
func ExampleMarshalIndent() {
	type ColorGroup struct {
		ID     int
		Name   string
		Colors []string
	}
	group := ColorGroup{
		ID:     1,
		Name:   "Reds",
		Colors: []string{"Crimson", "Red", "Ruby", "Maroon", "Dark amber"},
	}
	b, err := rjson.MarshalIndent(group, "", "\t")
	if err != nil {
		fmt.Println("error:", err)
	}
	os.Stdout.Write(b)
	// Output:
	// {
	// 	ID: 1
	// 	Name: "Reds"
	// 	Colors: [
	// 		"Crimson"
	// 		"Red"
	// 		"Ruby"
	// 		"Maroon"
	// 		"Dark amber"
	// 	]
	// }
}
Beispiel #2
0
func main() {
	flag.Parse()
	if flag.NArg() > 0 {
		fmt.Fprintf(os.Stderr, "rjson reads from stdin only")
		os.Exit(2)
	}
	var marshal func(interface{}) ([]byte, error)
	if *jsonOut {
		if *indent == "" {
			marshal = json.Marshal
		} else {
			marshal = func(v interface{}) ([]byte, error) {
				return json.MarshalIndent(v, "", *indent)
			}
		}
	} else {
		if *indent == "" {
			marshal = func(v interface{}) ([]byte, error) {
				data, err := rjson.MarshalIndent(v, "", "")
				if err != nil {
					return data, err
				}
				// TODO: use Compact only when it compacts
				// identifiers too.
				var b bytes.Buffer
				if err := rjson.Compact(&b, data); err != nil {
					return nil, err
				}
				return b.Bytes(), nil
			}
		} else {
			marshal = func(v interface{}) ([]byte, error) {
				return rjson.MarshalIndent(v, "", *indent)
			}
		}
	}
	d := rjson.NewDecoder(os.Stdin)
	d.UseNumber()
	w := bufio.NewWriter(os.Stdout)

	err := stream(w, d, marshal)
	if err != nil {
		fmt.Fprintf(os.Stderr, "rjson: %v", err)
		os.Exit(1)
	}
}