github.com/MangoDowner/go-gm@v0.0.0-20180818020936-8baa2bd4408c/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 a Decoder to decode a stream of distinct JSON values.
    87  func ExampleDecoder_Token() {
    88  	const jsonStream = `
    89  		{"Message": "Hello", "Array": [1, 2, 3], "Null": null, "Number": 1.234}
    90  	`
    91  	dec := json.NewDecoder(strings.NewReader(jsonStream))
    92  	for {
    93  		t, err := dec.Token()
    94  		if err == io.EOF {
    95  			break
    96  		}
    97  		if err != nil {
    98  			log.Fatal(err)
    99  		}
   100  		fmt.Printf("%T: %v", t, t)
   101  		if dec.More() {
   102  			fmt.Printf(" (more)")
   103  		}
   104  		fmt.Printf("\n")
   105  	}
   106  	// Output:
   107  	// json.Delim: { (more)
   108  	// string: Message (more)
   109  	// string: Hello (more)
   110  	// string: Array (more)
   111  	// json.Delim: [ (more)
   112  	// float64: 1 (more)
   113  	// float64: 2 (more)
   114  	// float64: 3
   115  	// json.Delim: ] (more)
   116  	// string: Null (more)
   117  	// <nil>: <nil> (more)
   118  	// string: Number (more)
   119  	// float64: 1.234
   120  	// json.Delim: }
   121  }
   122  
   123  // This example uses a Decoder to decode a streaming array of JSON objects.
   124  func ExampleDecoder_Decode_stream() {
   125  	const jsonStream = `
   126  	[
   127  		{"Name": "Ed", "Text": "Knock knock."},
   128  		{"Name": "Sam", "Text": "Who's there?"},
   129  		{"Name": "Ed", "Text": "Go fmt."},
   130  		{"Name": "Sam", "Text": "Go fmt who?"},
   131  		{"Name": "Ed", "Text": "Go fmt yourself!"}
   132  	]
   133  `
   134  	type Message struct {
   135  		Name, Text string
   136  	}
   137  	dec := json.NewDecoder(strings.NewReader(jsonStream))
   138  
   139  	// read open bracket
   140  	t, err := dec.Token()
   141  	if err != nil {
   142  		log.Fatal(err)
   143  	}
   144  	fmt.Printf("%T: %v\n", t, t)
   145  
   146  	// while the array contains values
   147  	for dec.More() {
   148  		var m Message
   149  		// decode an array value (Message)
   150  		err := dec.Decode(&m)
   151  		if err != nil {
   152  			log.Fatal(err)
   153  		}
   154  
   155  		fmt.Printf("%v: %v\n", m.Name, m.Text)
   156  	}
   157  
   158  	// read closing bracket
   159  	t, err = dec.Token()
   160  	if err != nil {
   161  		log.Fatal(err)
   162  	}
   163  	fmt.Printf("%T: %v\n", t, t)
   164  
   165  	// Output:
   166  	// json.Delim: [
   167  	// Ed: Knock knock.
   168  	// Sam: Who's there?
   169  	// Ed: Go fmt.
   170  	// Sam: Go fmt who?
   171  	// Ed: Go fmt yourself!
   172  	// json.Delim: ]
   173  
   174  }
   175  
   176  // This example uses RawMessage to delay parsing part of a JSON message.
   177  func ExampleRawMessage_unmarshal() {
   178  	type Color struct {
   179  		Space string
   180  		Point json.RawMessage // delay parsing until we know the color space
   181  	}
   182  	type RGB struct {
   183  		R uint8
   184  		G uint8
   185  		B uint8
   186  	}
   187  	type YCbCr struct {
   188  		Y  uint8
   189  		Cb int8
   190  		Cr int8
   191  	}
   192  
   193  	var j = []byte(`[
   194  		{"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}},
   195  		{"Space": "RGB",   "Point": {"R": 98, "G": 218, "B": 255}}
   196  	]`)
   197  	var colors []Color
   198  	err := json.Unmarshal(j, &colors)
   199  	if err != nil {
   200  		log.Fatalln("error:", err)
   201  	}
   202  
   203  	for _, c := range colors {
   204  		var dst interface{}
   205  		switch c.Space {
   206  		case "RGB":
   207  			dst = new(RGB)
   208  		case "YCbCr":
   209  			dst = new(YCbCr)
   210  		}
   211  		err := json.Unmarshal(c.Point, dst)
   212  		if err != nil {
   213  			log.Fatalln("error:", err)
   214  		}
   215  		fmt.Println(c.Space, dst)
   216  	}
   217  	// Output:
   218  	// YCbCr &{255 0 -10}
   219  	// RGB &{98 218 255}
   220  }
   221  
   222  // This example uses RawMessage to use a precomputed JSON during marshal.
   223  func ExampleRawMessage_marshal() {
   224  	h := json.RawMessage(`{"precomputed": true}`)
   225  
   226  	c := struct {
   227  		Header *json.RawMessage `json:"header"`
   228  		Body   string           `json:"body"`
   229  	}{Header: &h, Body: "Hello Gophers!"}
   230  
   231  	b, err := json.MarshalIndent(&c, "", "\t")
   232  	if err != nil {
   233  		fmt.Println("error:", err)
   234  	}
   235  	os.Stdout.Write(b)
   236  
   237  	// Output:
   238  	// {
   239  	// 	"header": {
   240  	// 		"precomputed": true
   241  	// 	},
   242  	// 	"body": "Hello Gophers!"
   243  	// }
   244  }
   245  
   246  func ExampleIndent() {
   247  	type Road struct {
   248  		Name   string
   249  		Number int
   250  	}
   251  	roads := []Road{
   252  		{"Diamond Fork", 29},
   253  		{"Sheep Creek", 51},
   254  	}
   255  
   256  	b, err := json.Marshal(roads)
   257  	if err != nil {
   258  		log.Fatal(err)
   259  	}
   260  
   261  	var out bytes.Buffer
   262  	json.Indent(&out, b, "=", "\t")
   263  	out.WriteTo(os.Stdout)
   264  	// Output:
   265  	// [
   266  	// =	{
   267  	// =		"Name": "Diamond Fork",
   268  	// =		"Number": 29
   269  	// =	},
   270  	// =	{
   271  	// =		"Name": "Sheep Creek",
   272  	// =		"Number": 51
   273  	// =	}
   274  	// =]
   275  }