Debian Codegraph @

src/encoding/json/v2_example_test.go

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