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