Source file src/encoding/json/example_test.go

     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  // This example uses RawMessage to delay parsing part of a JSON message.
   176  func ExampleRawMessage_unmarshal() {
   177  	type Color struct {
   178  		Space string
   179  		Point json.RawMessage // delay parsing until we know the color space
   180  	}
   181  	type RGB struct {
   182  		R uint8
   183  		G uint8
   184  		B uint8
   185  	}
   186  	type YCbCr struct {
   187  		Y  uint8
   188  		Cb int8
   189  		Cr int8
   190  	}
   191  
   192  	var j = []byte(`[
   193  	{"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}},
   194  	{"Space": "RGB",   "Point": {"R": 98, "G": 218, "B": 255}}
   195  ]`)
   196  	var colors []Color
   197  	err := json.Unmarshal(j, &colors)
   198  	if err != nil {
   199  		log.Fatalln("error:", err)
   200  	}
   201  
   202  	for _, c := range colors {
   203  		var dst any
   204  		switch c.Space {
   205  		case "RGB":
   206  			dst = new(RGB)
   207  		case "YCbCr":
   208  			dst = new(YCbCr)
   209  		}
   210  		err := json.Unmarshal(c.Point, dst)
   211  		if err != nil {
   212  			log.Fatalln("error:", err)
   213  		}
   214  		fmt.Println(c.Space, dst)
   215  	}
   216  	// Output:
   217  	// YCbCr &{255 0 -10}
   218  	// RGB &{98 218 255}
   219  }
   220  
   221  // This example uses RawMessage to use a precomputed JSON during marshal.
   222  func ExampleRawMessage_marshal() {
   223  	h := json.RawMessage(`{"precomputed": true}`)
   224  
   225  	c := struct {
   226  		Header *json.RawMessage `json:"header"`
   227  		Body   string           `json:"body"`
   228  	}{Header: &h, Body: "Hello Gophers!"}
   229  
   230  	b, err := json.MarshalIndent(&c, "", "\t")
   231  	if err != nil {
   232  		fmt.Println("error:", err)
   233  	}
   234  	os.Stdout.Write(b)
   235  
   236  	// Output:
   237  	// {
   238  	// 	"header": {
   239  	// 		"precomputed": true
   240  	// 	},
   241  	// 	"body": "Hello Gophers!"
   242  	// }
   243  }
   244  
   245  func ExampleIndent() {
   246  	type Road struct {
   247  		Name   string
   248  		Number int
   249  	}
   250  	roads := []Road{
   251  		{"Diamond Fork", 29},
   252  		{"Sheep Creek", 51},
   253  	}
   254  
   255  	b, err := json.Marshal(roads)
   256  	if err != nil {
   257  		log.Fatal(err)
   258  	}
   259  
   260  	var out bytes.Buffer
   261  	json.Indent(&out, b, "=", "\t")
   262  	out.WriteTo(os.Stdout)
   263  	// Output:
   264  	// [
   265  	// =	{
   266  	// =		"Name": "Diamond Fork",
   267  	// =		"Number": 29
   268  	// =	},
   269  	// =	{
   270  	// =		"Name": "Sheep Creek",
   271  	// =		"Number": 51
   272  	// =	}
   273  	// =]
   274  }
   275  
   276  func ExampleMarshalIndent() {
   277  	data := map[string]int{
   278  		"a": 1,
   279  		"b": 2,
   280  	}
   281  
   282  	b, err := json.MarshalIndent(data, "<prefix>", "<indent>")
   283  	if err != nil {
   284  		log.Fatal(err)
   285  	}
   286  
   287  	fmt.Println(string(b))
   288  	// Output:
   289  	// {
   290  	// <prefix><indent>"a": 1,
   291  	// <prefix><indent>"b": 2
   292  	// <prefix>}
   293  }
   294  
   295  func ExampleValid() {
   296  	goodJSON := `{"example": 1}`
   297  	badJSON := `{"example":2:]}}`
   298  
   299  	fmt.Println(json.Valid([]byte(goodJSON)), json.Valid([]byte(badJSON)))
   300  	// Output:
   301  	// true false
   302  }
   303  
   304  func ExampleHTMLEscape() {
   305  	var out bytes.Buffer
   306  	json.HTMLEscape(&out, []byte(`{"Name":"<b>HTML content</b>"}`))
   307  	out.WriteTo(os.Stdout)
   308  	// Output:
   309  	//{"Name":"\u003cb\u003eHTML content\u003c/b\u003e"}
   310  }
   311  

View as plain text