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