Source file
src/encoding/json/v2_example_test.go
1
2
3
4
5
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
37
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
56
57 }
58
59
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
82
83
84
85
86
87 }
88
89
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124 }
125
126
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
143 t, err := dec.Token()
144 if err != nil {
145 log.Fatal(err)
146 }
147 fmt.Printf("%T: %v\n", t, t)
148
149
150 for dec.More() {
151 var m Message
152
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
162 t, err = dec.Token()
163 if err != nil {
164 log.Fatal(err)
165 }
166 fmt.Printf("%T: %v\n", t, t)
167
168
169
170
171
172
173
174
175
176 }
177
178
179 func ExampleRawMessage_unmarshal() {
180 type Color struct {
181 Space string
182 Point json.RawMessage
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
220
221
222 }
223
224
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
240
241
242
243
244
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
267
268
269
270
271
272
273
274
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
292
293
294
295
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
304
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
312
313 }
314
View as plain text