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  //go:build !goexperiment.jsonv2
     6  
     7  package json_test
     8  
     9  import (
    10  	"bytes"
    11  	"encoding/json"
    12  	"fmt"
    13  	"io"
    14  	"log"
    15  	"os"
    16  	"strings"
    17  )
    18  
    19  func ExampleMarshal() {
    20  	type ColorGroup struct {
    21  		ID     int
    22  		Name   string
    23  		Colors []string
    24  	}
    25  	group := ColorGroup{
    26  		ID:     1,
    27  		Name:   "Reds",
    28  		Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
    29  	}
    30  	b, err := json.Marshal(group)
    31  	if err != nil {
    32  		fmt.Println("error:", err)
    33  	}
    34  	os.Stdout.Write(b)
    35  	// Output:
    36  	// {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
    37  }
    38  
    39  func ExampleUnmarshal() {
    40  	var jsonBlob = []byte(`[
    41  	{"Name": "Platypus", "Order": "Monotremata"},
    42  	{"Name": "Quoll",    "Order": "Dasyuromorphia"}
    43  ]`)
    44  	type Animal struct {
    45  		Name  string
    46  		Order string
    47  	}
    48  	var animals []Animal
    49  	err := json.Unmarshal(jsonBlob, &animals)
    50  	if err != nil {
    51  		fmt.Println("error:", err)
    52  	}
    53  	fmt.Printf("%+v", animals)
    54  	// Output:
    55  	// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
    56  }
    57  
    58  // This example uses a Decoder to decode a stream of distinct JSON values.
    59  func ExampleDecoder() {
    60  	const jsonStream = `
    61  	{"Name": "Ed", "Text": "Knock knock."}
    62  	{"Name": "Sam", "Text": "Who's there?"}
    63  	{"Name": "Ed", "Text": "Go fmt."}
    64  	{"Name": "Sam", "Text": "Go fmt who?"}
    65  	{"Name": "Ed", "Text": "Go fmt yourself!"}
    66  `
    67  	type Message struct {
    68  		Name, Text string
    69  	}
    70  	dec := json.NewDecoder(strings.NewReader(jsonStream))
    71  	for {
    72  		var m Message
    73  		if err := dec.Decode(&m); err == io.EOF {
    74  			break
    75  		} else if err != nil {
    76  			log.Fatal(err)
    77  		}
    78  		fmt.Printf("%s: %s\n", m.Name, m.Text)
    79  	}
    80  	// Output:
    81  	// Ed: Knock knock.
    82  	// Sam: Who's there?
    83  	// Ed: Go fmt.
    84  	// Sam: Go fmt who?
    85  	// Ed: Go fmt yourself!
    86  }
    87  
    88  // This example uses a Decoder to decode a stream of distinct JSON values.
    89  func ExampleDecoder_Token() {
    90  	const jsonStream = `
    91  	{"Message": "Hello", "Array": [1, 2, 3], "Null": null, "Number": 1.234}
    92  `
    93  	dec := json.NewDecoder(strings.NewReader(jsonStream))
    94  	for {
    95  		t, err := dec.Token()
    96  		if err == io.EOF {
    97  			break
    98  		}
    99  		if err != nil {
   100  			log.Fatal(err)
   101  		}
   102  		fmt.Printf("%T: %v", t, t)
   103  		if dec.More() {
   104  			fmt.Printf(" (more)")
   105  		}
   106  		fmt.Printf("\n")
   107  	}
   108  	// Output:
   109  	// json.Delim: { (more)
   110  	// string: Message (more)
   111  	// string: Hello (more)
   112  	// string: Array (more)
   113  	// json.Delim: [ (more)
   114  	// float64: 1 (more)
   115  	// float64: 2 (more)
   116  	// float64: 3
   117  	// json.Delim: ] (more)
   118  	// string: Null (more)
   119  	// <nil>: <nil> (more)
   120  	// string: Number (more)
   121  	// float64: 1.234
   122  	// json.Delim: }
   123  }
   124  
   125  // This example uses a Decoder to decode a streaming array of JSON objects.
   126  func ExampleDecoder_Decode_stream() {
   127  	const jsonStream = `
   128  	[
   129  		{"Name": "Ed", "Text": "Knock knock."},
   130  		{"Name": "Sam", "Text": "Who's there?"},
   131  		{"Name": "Ed", "Text": "Go fmt."},
   132  		{"Name": "Sam", "Text": "Go fmt who?"},
   133  		{"Name": "Ed", "Text": "Go fmt yourself!"}
   134  	]
   135  `
   136  	type Message struct {
   137  		Name, Text string
   138  	}
   139  	dec := json.NewDecoder(strings.NewReader(jsonStream))
   140  
   141  	// read open bracket
   142  	t, err := dec.Token()
   143  	if err != nil {
   144  		log.Fatal(err)
   145  	}
   146  	fmt.Printf("%T: %v\n", t, t)
   147  
   148  	// while the array contains values
   149  	for dec.More() {
   150  		var m Message
   151  		// decode an array value (Message)
   152  		err := dec.Decode(&m)
   153  		if err != nil {
   154  			log.Fatal(err)
   155  		}
   156  
   157  		fmt.Printf("%v: %v\n", m.Name, m.Text)
   158  	}
   159  
   160  	// read closing bracket
   161  	t, err = dec.Token()
   162  	if err != nil {
   163  		log.Fatal(err)
   164  	}
   165  	fmt.Printf("%T: %v\n", t, t)
   166  
   167  	// Output:
   168  	// json.Delim: [
   169  	// Ed: Knock knock.
   170  	// Sam: Who's there?
   171  	// Ed: Go fmt.
   172  	// Sam: Go fmt who?
   173  	// Ed: Go fmt yourself!
   174  	// json.Delim: ]
   175  }
   176  
   177  // This example uses RawMessage to delay parsing part of a JSON message.
   178  func ExampleRawMessage_unmarshal() {
   179  	type Color struct {
   180  		Space string
   181  		Point json.RawMessage // delay parsing until we know the color space
   182  	}
   183  	type RGB struct {
   184  		R uint8
   185  		G uint8
   186  		B uint8
   187  	}
   188  	type YCbCr struct {
   189  		Y  uint8
   190  		Cb int8
   191  		Cr int8
   192  	}
   193  
   194  	var j = []byte(`[
   195  	{"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}},
   196  	{"Space": "RGB",   "Point": {"R": 98, "G": 218, "B": 255}}
   197  ]`)
   198  	var colors []Color
   199  	err := json.Unmarshal(j, &colors)
   200  	if err != nil {
   201  		log.Fatalln("error:", err)
   202  	}
   203  
   204  	for _, c := range colors {
   205  		var dst any
   206  		switch c.Space {
   207  		case "RGB":
   208  			dst = new(RGB)
   209  		case "YCbCr":
   210  			dst = new(YCbCr)
   211  		}
   212  		err := json.Unmarshal(c.Point, dst)
   213  		if err != nil {
   214  			log.Fatalln("error:", err)
   215  		}
   216  		fmt.Println(c.Space, dst)
   217  	}
   218  	// Output:
   219  	// YCbCr &{255 0 -10}
   220  	// RGB &{98 218 255}
   221  }
   222  
   223  // This example uses RawMessage to use a precomputed JSON during marshal.
   224  func ExampleRawMessage_marshal() {
   225  	h := json.RawMessage(`{"precomputed": true}`)
   226  
   227  	c := struct {
   228  		Header *json.RawMessage `json:"header"`
   229  		Body   string           `json:"body"`
   230  	}{Header: &h, Body: "Hello Gophers!"}
   231  
   232  	b, err := json.MarshalIndent(&c, "", "\t")
   233  	if err != nil {
   234  		fmt.Println("error:", err)
   235  	}
   236  	os.Stdout.Write(b)
   237  
   238  	// Output:
   239  	// {
   240  	// 	"header": {
   241  	// 		"precomputed": true
   242  	// 	},
   243  	// 	"body": "Hello Gophers!"
   244  	// }
   245  }
   246  
   247  func ExampleIndent() {
   248  	type Road struct {
   249  		Name   string
   250  		Number int
   251  	}
   252  	roads := []Road{
   253  		{"Diamond Fork", 29},
   254  		{"Sheep Creek", 51},
   255  	}
   256  
   257  	b, err := json.Marshal(roads)
   258  	if err != nil {
   259  		log.Fatal(err)
   260  	}
   261  
   262  	var out bytes.Buffer
   263  	json.Indent(&out, b, "=", "\t")
   264  	out.WriteTo(os.Stdout)
   265  	// Output:
   266  	// [
   267  	// =	{
   268  	// =		"Name": "Diamond Fork",
   269  	// =		"Number": 29
   270  	// =	},
   271  	// =	{
   272  	// =		"Name": "Sheep Creek",
   273  	// =		"Number": 51
   274  	// =	}
   275  	// =]
   276  }
   277  
   278  func ExampleMarshalIndent() {
   279  	data := map[string]int{
   280  		"a": 1,
   281  		"b": 2,
   282  	}
   283  
   284  	b, err := json.MarshalIndent(data, "<prefix>", "<indent>")
   285  	if err != nil {
   286  		log.Fatal(err)
   287  	}
   288  
   289  	fmt.Println(string(b))
   290  	// Output:
   291  	// {
   292  	// <prefix><indent>"a": 1,
   293  	// <prefix><indent>"b": 2
   294  	// <prefix>}
   295  }
   296  
   297  func ExampleValid() {
   298  	goodJSON := `{"example": 1}`
   299  	badJSON := `{"example":2:]}}`
   300  
   301  	fmt.Println(json.Valid([]byte(goodJSON)), json.Valid([]byte(badJSON)))
   302  	// Output:
   303  	// true false
   304  }
   305  
   306  func ExampleHTMLEscape() {
   307  	var out bytes.Buffer
   308  	json.HTMLEscape(&out, []byte(`{"Name":"<b>HTML content</b>"}`))
   309  	out.WriteTo(os.Stdout)
   310  	// Output:
   311  	//{"Name":"\u003cb\u003eHTML content\u003c/b\u003e"}
   312  }
   313  

View as plain text