github.com/bgentry/go@v0.0.0-20150121062915-6cf5a733d54d/src/encoding/json/example_test.go (about)

     1  // Copyright 2011 The Go Authors.  All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package json_test
     6  
     7  import (
     8  	"bytes"
     9  	"encoding/json"
    10  	"fmt"
    11  	"io"
    12  	"log"
    13  	"os"
    14  	"strings"
    15  )
    16  
    17  func ExampleMarshal() {
    18  	type ColorGroup struct {
    19  		ID     int
    20  		Name   string
    21  		Colors []string
    22  	}
    23  	group := ColorGroup{
    24  		ID:     1,
    25  		Name:   "Reds",
    26  		Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
    27  	}
    28  	b, err := json.Marshal(group)
    29  	if err != nil {
    30  		fmt.Println("error:", err)
    31  	}
    32  	os.Stdout.Write(b)
    33  	// Output:
    34  	// {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
    35  }
    36  
    37  func ExampleUnmarshal() {
    38  	var jsonBlob = []byte(`[
    39  		{"Name": "Platypus", "Order": "Monotremata"},
    40  		{"Name": "Quoll",    "Order": "Dasyuromorphia"}
    41  	]`)
    42  	type Animal struct {
    43  		Name  string
    44  		Order string
    45  	}
    46  	var animals []Animal
    47  	err := json.Unmarshal(jsonBlob, &animals)
    48  	if err != nil {
    49  		fmt.Println("error:", err)
    50  	}
    51  	fmt.Printf("%+v", animals)
    52  	// Output:
    53  	// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
    54  }
    55  
    56  // This example uses a Decoder to decode a stream of distinct JSON values.
    57  func ExampleDecoder() {
    58  	const jsonStream = `
    59  		{"Name": "Ed", "Text": "Knock knock."}
    60  		{"Name": "Sam", "Text": "Who's there?"}
    61  		{"Name": "Ed", "Text": "Go fmt."}
    62  		{"Name": "Sam", "Text": "Go fmt who?"}
    63  		{"Name": "Ed", "Text": "Go fmt yourself!"}
    64  	`
    65  	type Message struct {
    66  		Name, Text string
    67  	}
    68  	dec := json.NewDecoder(strings.NewReader(jsonStream))
    69  	for {
    70  		var m Message
    71  		if err := dec.Decode(&m); err == io.EOF {
    72  			break
    73  		} else if err != nil {
    74  			log.Fatal(err)
    75  		}
    76  		fmt.Printf("%s: %s\n", m.Name, m.Text)
    77  	}
    78  	// Output:
    79  	// Ed: Knock knock.
    80  	// Sam: Who's there?
    81  	// Ed: Go fmt.
    82  	// Sam: Go fmt who?
    83  	// Ed: Go fmt yourself!
    84  }
    85  
    86  // This example uses RawMessage to delay parsing part of a JSON message.
    87  func ExampleRawMessage() {
    88  	type Color struct {
    89  		Space string
    90  		Point json.RawMessage // delay parsing until we know the color space
    91  	}
    92  	type RGB struct {
    93  		R uint8
    94  		G uint8
    95  		B uint8
    96  	}
    97  	type YCbCr struct {
    98  		Y  uint8
    99  		Cb int8
   100  		Cr int8
   101  	}
   102  
   103  	var j = []byte(`[
   104  		{"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}},
   105  		{"Space": "RGB",   "Point": {"R": 98, "G": 218, "B": 255}}
   106  	]`)
   107  	var colors []Color
   108  	err := json.Unmarshal(j, &colors)
   109  	if err != nil {
   110  		log.Fatalln("error:", err)
   111  	}
   112  
   113  	for _, c := range colors {
   114  		var dst interface{}
   115  		switch c.Space {
   116  		case "RGB":
   117  			dst = new(RGB)
   118  		case "YCbCr":
   119  			dst = new(YCbCr)
   120  		}
   121  		err := json.Unmarshal(c.Point, dst)
   122  		if err != nil {
   123  			log.Fatalln("error:", err)
   124  		}
   125  		fmt.Println(c.Space, dst)
   126  	}
   127  	// Output:
   128  	// YCbCr &{255 0 -10}
   129  	// RGB &{98 218 255}
   130  }
   131  
   132  func ExampleIndent() {
   133  	type Road struct {
   134  		Name   string
   135  		Number int
   136  	}
   137  	roads := []Road{
   138  		{"Diamond Fork", 29},
   139  		{"Sheep Creek", 51},
   140  	}
   141  
   142  	b, err := json.Marshal(roads)
   143  	if err != nil {
   144  		log.Fatal(err)
   145  	}
   146  
   147  	var out bytes.Buffer
   148  	json.Indent(&out, b, "=", "\t")
   149  	out.WriteTo(os.Stdout)
   150  	// Output:
   151  	// [
   152  	// =	{
   153  	// =		"Name": "Diamond Fork",
   154  	// =		"Number": 29
   155  	// =	},
   156  	// =	{
   157  	// =		"Name": "Sheep Creek",
   158  	// =		"Number": 51
   159  	// =	}
   160  	// =]
   161  }