1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
|
<h1> Package json </h1> <ul id="short-nav">
<li><code>import "encoding/json"</code></li>
<li><a href="#pkg-overview" class="overviewLink">Overview</a></li>
<li><a href="#pkg-index" class="indexLink">Index</a></li>
<li><a href="#pkg-examples" class="examplesLink">Examples</a></li>
</ul> <h2 id="pkg-overview">Overview </h2> <p>Package json implements encoding and decoding of JSON as defined in RFC 7159. The mapping between JSON and Go values is described in the documentation for the Marshal and Unmarshal functions. </p>
<p>See "JSON and Go" for an introduction to this package: <a href="https://golang.org/doc/articles/json_and_go.html">https://golang.org/doc/articles/json_and_go.html</a> </p> <h4 id="example__customMarshalJSON"> <span class="text">Example (CustomMarshalJSON)</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">package json_test
import (
"encoding/json"
"fmt"
"log"
"strings"
)
type Animal int
const (
Unknown Animal = iota
Gopher
Zebra
)
func (a *Animal) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
switch strings.ToLower(s) {
default:
*a = Unknown
case "gopher":
*a = Gopher
case "zebra":
*a = Zebra
}
return nil
}
func (a Animal) MarshalJSON() ([]byte, error) {
var s string
switch a {
default:
s = "unknown"
case Gopher:
s = "gopher"
case Zebra:
s = "zebra"
}
return json.Marshal(s)
}
func Example_customMarshalJSON() {
blob := `["gopher","armadillo","zebra","unknown","gopher","bee","gopher","zebra"]`
var zoo []Animal
if err := json.Unmarshal([]byte(blob), &zoo); err != nil {
log.Fatal(err)
}
census := make(map[Animal]int)
for _, animal := range zoo {
census[animal] += 1
}
fmt.Printf("Zoo Census:\n* Gophers: %d\n* Zebras: %d\n* Unknown: %d\n",
census[Gopher], census[Zebra], census[Unknown])
// Output:
// Zoo Census:
// * Gophers: 3
// * Zebras: 2
// * Unknown: 3
}
</pre> <h4 id="example__textMarshalJSON"> <span class="text">Example (TextMarshalJSON)</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">package json_test
import (
"encoding/json"
"fmt"
"log"
"strings"
)
type Size int
const (
Unrecognized Size = iota
Small
Large
)
func (s *Size) UnmarshalText(text []byte) error {
switch strings.ToLower(string(text)) {
default:
*s = Unrecognized
case "small":
*s = Small
case "large":
*s = Large
}
return nil
}
func (s Size) MarshalText() ([]byte, error) {
var name string
switch s {
default:
name = "unrecognized"
case Small:
name = "small"
case Large:
name = "large"
}
return []byte(name), nil
}
func Example_textMarshalJSON() {
blob := `["small","regular","large","unrecognized","small","normal","small","large"]`
var inventory []Size
if err := json.Unmarshal([]byte(blob), &inventory); err != nil {
log.Fatal(err)
}
counts := make(map[Size]int)
for _, size := range inventory {
counts[size] += 1
}
fmt.Printf("Inventory Counts:\n* Small: %d\n* Large: %d\n* Unrecognized: %d\n",
counts[Small], counts[Large], counts[Unrecognized])
// Output:
// Inventory Counts:
// * Small: 3
// * Large: 2
// * Unrecognized: 3
}
</pre> <h2 id="pkg-index">Index </h2> <ul id="manual-nav">
<li><a href="#Compact">func Compact(dst *bytes.Buffer, src []byte) error</a></li>
<li><a href="#HTMLEscape">func HTMLEscape(dst *bytes.Buffer, src []byte)</a></li>
<li><a href="#Indent">func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error</a></li>
<li><a href="#Marshal">func Marshal(v any) ([]byte, error)</a></li>
<li><a href="#MarshalIndent">func MarshalIndent(v any, prefix, indent string) ([]byte, error)</a></li>
<li><a href="#Unmarshal">func Unmarshal(data []byte, v any) error</a></li>
<li><a href="#Valid">func Valid(data []byte) bool</a></li>
<li><a href="#Decoder">type Decoder</a></li>
<li> <a href="#NewDecoder">func NewDecoder(r io.Reader) *Decoder</a>
</li>
<li> <a href="#Decoder.Buffered">func (dec *Decoder) Buffered() io.Reader</a>
</li>
<li> <a href="#Decoder.Decode">func (dec *Decoder) Decode(v any) error</a>
</li>
<li> <a href="#Decoder.DisallowUnknownFields">func (dec *Decoder) DisallowUnknownFields()</a>
</li>
<li> <a href="#Decoder.InputOffset">func (dec *Decoder) InputOffset() int64</a>
</li>
<li> <a href="#Decoder.More">func (dec *Decoder) More() bool</a>
</li>
<li> <a href="#Decoder.Token">func (dec *Decoder) Token() (Token, error)</a>
</li>
<li> <a href="#Decoder.UseNumber">func (dec *Decoder) UseNumber()</a>
</li>
<li><a href="#Delim">type Delim</a></li>
<li> <a href="#Delim.String">func (d Delim) String() string</a>
</li>
<li><a href="#Encoder">type Encoder</a></li>
<li> <a href="#NewEncoder">func NewEncoder(w io.Writer) *Encoder</a>
</li>
<li> <a href="#Encoder.Encode">func (enc *Encoder) Encode(v any) error</a>
</li>
<li> <a href="#Encoder.SetEscapeHTML">func (enc *Encoder) SetEscapeHTML(on bool)</a>
</li>
<li> <a href="#Encoder.SetIndent">func (enc *Encoder) SetIndent(prefix, indent string)</a>
</li>
<li><a href="#InvalidUTF8Error">type InvalidUTF8Error</a></li>
<li> <a href="#InvalidUTF8Error.Error">func (e *InvalidUTF8Error) Error() string</a>
</li>
<li><a href="#InvalidUnmarshalError">type InvalidUnmarshalError</a></li>
<li> <a href="#InvalidUnmarshalError.Error">func (e *InvalidUnmarshalError) Error() string</a>
</li>
<li><a href="#Marshaler">type Marshaler</a></li>
<li><a href="#MarshalerError">type MarshalerError</a></li>
<li> <a href="#MarshalerError.Error">func (e *MarshalerError) Error() string</a>
</li>
<li> <a href="#MarshalerError.Unwrap">func (e *MarshalerError) Unwrap() error</a>
</li>
<li><a href="#Number">type Number</a></li>
<li> <a href="#Number.Float64">func (n Number) Float64() (float64, error)</a>
</li>
<li> <a href="#Number.Int64">func (n Number) Int64() (int64, error)</a>
</li>
<li> <a href="#Number.String">func (n Number) String() string</a>
</li>
<li><a href="#RawMessage">type RawMessage</a></li>
<li> <a href="#RawMessage.MarshalJSON">func (m RawMessage) MarshalJSON() ([]byte, error)</a>
</li>
<li> <a href="#RawMessage.UnmarshalJSON">func (m *RawMessage) UnmarshalJSON(data []byte) error</a>
</li>
<li><a href="#SyntaxError">type SyntaxError</a></li>
<li> <a href="#SyntaxError.Error">func (e *SyntaxError) Error() string</a>
</li>
<li><a href="#Token">type Token</a></li>
<li><a href="#UnmarshalFieldError">type UnmarshalFieldError</a></li>
<li> <a href="#UnmarshalFieldError.Error">func (e *UnmarshalFieldError) Error() string</a>
</li>
<li><a href="#UnmarshalTypeError">type UnmarshalTypeError</a></li>
<li> <a href="#UnmarshalTypeError.Error">func (e *UnmarshalTypeError) Error() string</a>
</li>
<li><a href="#Unmarshaler">type Unmarshaler</a></li>
<li><a href="#UnsupportedTypeError">type UnsupportedTypeError</a></li>
<li> <a href="#UnsupportedTypeError.Error">func (e *UnsupportedTypeError) Error() string</a>
</li>
<li><a href="#UnsupportedValueError">type UnsupportedValueError</a></li>
<li> <a href="#UnsupportedValueError.Error">func (e *UnsupportedValueError) Error() string</a>
</li>
</ul> <div id="pkg-examples"> <h3>Examples</h3> <dl> <dd><a class="exampleLink" href="#example_Decoder">Decoder</a></dd> <dd><a class="exampleLink" href="#example_Decoder_Decode_stream">Decoder.Decode (Stream)</a></dd> <dd><a class="exampleLink" href="#example_Decoder_Token">Decoder.Token</a></dd> <dd><a class="exampleLink" href="#example_HTMLEscape">HTMLEscape</a></dd> <dd><a class="exampleLink" href="#example_Indent">Indent</a></dd> <dd><a class="exampleLink" href="#example_Marshal">Marshal</a></dd> <dd><a class="exampleLink" href="#example_MarshalIndent">MarshalIndent</a></dd> <dd><a class="exampleLink" href="#example_RawMessage_marshal">RawMessage (Marshal)</a></dd> <dd><a class="exampleLink" href="#example_RawMessage_unmarshal">RawMessage (Unmarshal)</a></dd> <dd><a class="exampleLink" href="#example_Unmarshal">Unmarshal</a></dd> <dd><a class="exampleLink" href="#example_Valid">Valid</a></dd> <dd><a class="exampleLink" href="#example__customMarshalJSON">Package (CustomMarshalJSON)</a></dd> <dd><a class="exampleLink" href="#example__textMarshalJSON">Package (TextMarshalJSON)</a></dd> </dl> </div> <h3>Package files</h3> <p> <span>decode.go</span> <span>encode.go</span> <span>fold.go</span> <span>indent.go</span> <span>scanner.go</span> <span>stream.go</span> <span>tables.go</span> <span>tags.go</span> </p> <h2 id="Compact">func <span>Compact</span> </h2> <pre data-language="go">func Compact(dst *bytes.Buffer, src []byte) error</pre> <p>Compact appends to dst the JSON-encoded src with insignificant space characters elided. </p>
<h2 id="HTMLEscape">func <span>HTMLEscape</span> </h2> <pre data-language="go">func HTMLEscape(dst *bytes.Buffer, src []byte)</pre> <p>HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 so that the JSON will be safe to embed inside HTML <script> tags. For historical reasons, web browsers don't honor standard HTML escaping within <script> tags, so an alternative JSON encoding must be used. </p> <h4 id="example_HTMLEscape"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">var out bytes.Buffer
json.HTMLEscape(&out, []byte(`{"Name":"<b>HTML content</b>"}`))
out.WriteTo(os.Stdout)
</pre> <p>Output:</p> <pre class="output" data-language="go">{"Name":"\u003cb\u003eHTML content\u003c/b\u003e"}
</pre> <h2 id="Indent">func <span>Indent</span> </h2> <pre data-language="go">func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error</pre> <p>Indent appends to dst an indented form of the JSON-encoded src. Each element in a JSON object or array begins on a new, indented line beginning with prefix followed by one or more copies of indent according to the indentation nesting. The data appended to dst does not begin with the prefix nor any indentation, to make it easier to embed inside other formatted JSON data. Although leading space characters (space, tab, carriage return, newline) at the beginning of src are dropped, trailing space characters at the end of src are preserved and copied to dst. For example, if src has no trailing spaces, neither will dst; if src ends in a trailing newline, so will dst. </p> <h4 id="example_Indent"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">type Road struct {
Name string
Number int
}
roads := []Road{
{"Diamond Fork", 29},
{"Sheep Creek", 51},
}
b, err := json.Marshal(roads)
if err != nil {
log.Fatal(err)
}
var out bytes.Buffer
json.Indent(&out, b, "=", "\t")
out.WriteTo(os.Stdout)
</pre> <p>Output:</p> <pre class="output" data-language="go">[
= {
= "Name": "Diamond Fork",
= "Number": 29
= },
= {
= "Name": "Sheep Creek",
= "Number": 51
= }
=]
</pre> <h2 id="Marshal">func <span>Marshal</span> </h2> <pre data-language="go">func Marshal(v any) ([]byte, error)</pre> <p>Marshal returns the JSON encoding of v. </p>
<p>Marshal traverses the value v recursively. If an encountered value implements <a href="#Marshaler">Marshaler</a> and is not a nil pointer, Marshal calls [Marshaler.MarshalJSON] to produce JSON. If no [Marshaler.MarshalJSON] method is present but the value implements <span>encoding.TextMarshaler</span> instead, Marshal calls <span>encoding.TextMarshaler.MarshalText</span> and encodes the result as a JSON string. The nil pointer exception is not strictly necessary but mimics a similar, necessary exception in the behavior of [Unmarshaler.UnmarshalJSON]. </p>
<p>Otherwise, Marshal uses the following type-dependent default encodings: </p>
<p>Boolean values encode as JSON booleans. </p>
<p>Floating point, integer, and <a href="#Number">Number</a> values encode as JSON numbers. NaN and +/-Inf values will return an <a href="#UnsupportedValueError">UnsupportedValueError</a>. </p>
<p>String values encode as JSON strings coerced to valid UTF-8, replacing invalid bytes with the Unicode replacement rune. So that the JSON will be safe to embed inside HTML <script> tags, the string is encoded using <a href="#HTMLEscape">HTMLEscape</a>, which replaces "<", ">", "&", U+2028, and U+2029 are escaped to "\u003c","\u003e", "\u0026", "\u2028", and "\u2029". This replacement can be disabled when using an <a href="#Encoder">Encoder</a>, by calling <a href="#Encoder.SetEscapeHTML">Encoder.SetEscapeHTML</a>(false). </p>
<p>Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value. </p>
<p>Struct values encode as JSON objects. Each exported struct field becomes a member of the object, using the field name as the object key, unless the field is omitted for one of the reasons given below. </p>
<p>The encoding of each struct field can be customized by the format string stored under the "json" key in the struct field's tag. The format string gives the name of the field, possibly followed by a comma-separated list of options. The name may be empty in order to specify options without overriding the default field name. </p>
<p>The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string. </p>
<p>As a special case, if the field tag is "-", the field is always omitted. Note that a field with name "-" can still be generated using the tag "-,". </p>
<p>Examples of struct field tags and their meanings: </p>
<pre data-language="go">// Field appears in JSON as key "myName".
Field int `json:"myName"`
// Field appears in JSON as key "myName" and
// the field is omitted from the object if its value is empty,
// as defined above.
Field int `json:"myName,omitempty"`
// Field appears in JSON as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
Field int `json:",omitempty"`
// Field is ignored by this package.
Field int `json:"-"`
// Field appears in JSON as key "-".
Field int `json:"-,"`
</pre> <p>The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, integer, or boolean types. This extra level of encoding is sometimes used when communicating with JavaScript programs: </p>
<pre data-language="go">Int64String int64 `json:",string"`
</pre> <p>The key name will be used if it's a non-empty string consisting of only Unicode letters, digits, and ASCII punctuation except quotation marks, backslash, and comma. </p>
<p>Embedded struct fields are usually marshaled as if their inner exported fields were fields in the outer struct, subject to the usual Go visibility rules amended as described in the next paragraph. An anonymous struct field with a name given in its JSON tag is treated as having that name, rather than being anonymous. An anonymous struct field of interface type is treated the same as having that type as its name, rather than being anonymous. </p>
<p>The Go visibility rules for struct fields are amended for JSON when deciding which field to marshal or unmarshal. If there are multiple fields at the same level, and that level is the least nested (and would therefore be the nesting level selected by the usual Go rules), the following extra rules apply: </p>
<p>1) Of those fields, if any are JSON-tagged, only tagged fields are considered, even if there are multiple untagged fields that would otherwise conflict. </p>
<p>2) If there is exactly one field (tagged or not according to the first rule), that is selected. </p>
<p>3) Otherwise there are multiple fields, and all are ignored; no error occurs. </p>
<p>Handling of anonymous struct fields is new in Go 1.1. Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of an anonymous struct field in both current and earlier versions, give the field a JSON tag of "-". </p>
<p>Map values encode as JSON objects. The map's key type must either be a string, an integer type, or implement <span>encoding.TextMarshaler</span>. The map keys are sorted and used as JSON object keys by applying the following rules, subject to the UTF-8 coercion described for string values above: </p>
<ul> <li>keys of any string type are used directly </li>
<li>
<span>encoding.TextMarshalers</span> are marshaled </li>
<li>integer keys are converted to strings </li>
</ul> <p>Pointer values encode as the value pointed to. A nil pointer encodes as the null JSON value. </p>
<p>Interface values encode as the value contained in the interface. A nil interface value encodes as the null JSON value. </p>
<p>Channel, complex, and function values cannot be encoded in JSON. Attempting to encode such a value causes Marshal to return an <a href="#UnsupportedTypeError">UnsupportedTypeError</a>. </p>
<p>JSON cannot represent cyclic data structures and Marshal does not handle them. Passing cyclic structures to Marshal will result in an error. </p> <h4 id="example_Marshal"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">type ColorGroup struct {
ID int
Name string
Colors []string
}
group := ColorGroup{
ID: 1,
Name: "Reds",
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
}
b, err := json.Marshal(group)
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
</pre> <p>Output:</p> <pre class="output" data-language="go">{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
</pre> <h2 id="MarshalIndent">func <span>MarshalIndent</span> </h2> <pre data-language="go">func MarshalIndent(v any, prefix, indent string) ([]byte, error)</pre> <p>MarshalIndent is like <a href="#Marshal">Marshal</a> but applies <a href="#Indent">Indent</a> to format the output. Each JSON element in the output will begin on a new line beginning with prefix followed by one or more copies of indent according to the indentation nesting. </p> <h4 id="example_MarshalIndent"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">data := map[string]int{
"a": 1,
"b": 2,
}
b, err := json.MarshalIndent(data, "<prefix>", "<indent>")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(b))
</pre> <p>Output:</p> <pre class="output" data-language="go">{
<prefix><indent>"a": 1,
<prefix><indent>"b": 2
<prefix>}
</pre> <h2 id="Unmarshal">func <span>Unmarshal</span> </h2> <pre data-language="go">func Unmarshal(data []byte, v any) error</pre> <p>Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an <a href="#InvalidUnmarshalError">InvalidUnmarshalError</a>. </p>
<p>Unmarshal uses the inverse of the encodings that <a href="#Marshal">Marshal</a> uses, allocating maps, slices, and pointers as necessary, with the following additional rules: </p>
<p>To unmarshal JSON into a pointer, Unmarshal first handles the case of the JSON being the JSON literal null. In that case, Unmarshal sets the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into the value pointed at by the pointer. If the pointer is nil, Unmarshal allocates a new value for it to point to. </p>
<p>To unmarshal JSON into a value implementing <a href="#Unmarshaler">Unmarshaler</a>, Unmarshal calls that value's [Unmarshaler.UnmarshalJSON] method, including when the input is a JSON null. Otherwise, if the value implements <span>encoding.TextUnmarshaler</span> and the input is a JSON quoted string, Unmarshal calls <span>encoding.TextUnmarshaler.UnmarshalText</span> with the unquoted form of the string. </p>
<p>To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by <a href="#Marshal">Marshal</a> (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. By default, object keys which don't have a corresponding struct field are ignored (see <a href="#Decoder.DisallowUnknownFields">Decoder.DisallowUnknownFields</a> for an alternative). </p>
<p>To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value: </p>
<ul> <li>bool, for JSON booleans </li>
<li>float64, for JSON numbers </li>
<li>string, for JSON strings </li>
<li>[]interface{}, for JSON arrays </li>
<li>map[string]interface{}, for JSON objects </li>
<li>nil for JSON null </li>
</ul> <p>To unmarshal a JSON array into a slice, Unmarshal resets the slice length to zero and then appends each element to the slice. As a special case, to unmarshal an empty JSON array into a slice, Unmarshal replaces the slice with a new empty slice. </p>
<p>To unmarshal a JSON array into a Go array, Unmarshal decodes JSON array elements into corresponding Go array elements. If the Go array is smaller than the JSON array, the additional JSON array elements are discarded. If the JSON array is smaller than the Go array, the additional Go array elements are set to zero values. </p>
<p>To unmarshal a JSON object into a map, Unmarshal first establishes a map to use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal reuses the existing map, keeping existing entries. Unmarshal then stores key-value pairs from the JSON object into the map. The map's key type must either be any string type, an integer, implement <a href="#Unmarshaler">json.Unmarshaler</a>, or implement <span>encoding.TextUnmarshaler</span>. </p>
<p>If the JSON-encoded data contain a syntax error, Unmarshal returns a <a href="#SyntaxError">SyntaxError</a>. </p>
<p>If a JSON value is not appropriate for a given target type, or if a JSON number overflows the target type, Unmarshal skips that field and completes the unmarshaling as best it can. If no more serious errors are encountered, Unmarshal returns an <a href="#UnmarshalTypeError">UnmarshalTypeError</a> describing the earliest such error. In any case, it's not guaranteed that all the remaining fields following the problematic one will be unmarshaled into the target object. </p>
<p>The JSON null value unmarshals into an interface, map, pointer, or slice by setting that Go value to nil. Because null is often used in JSON to mean “not present,” unmarshaling a JSON null into any other Go type has no effect on the value and produces no error. </p>
<p>When unmarshaling quoted strings, invalid UTF-8 or invalid UTF-16 surrogate pairs are not treated as an error. Instead, they are replaced by the Unicode replacement character U+FFFD. </p> <h4 id="example_Unmarshal"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">var jsonBlob = []byte(`[
{"Name": "Platypus", "Order": "Monotremata"},
{"Name": "Quoll", "Order": "Dasyuromorphia"}
]`)
type Animal struct {
Name string
Order string
}
var animals []Animal
err := json.Unmarshal(jsonBlob, &animals)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v", animals)
</pre> <p>Output:</p> <pre class="output" data-language="go">[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
</pre> <h2 id="Valid">func <span>Valid</span> <span title="Added in Go 1.9">1.9</span> </h2> <pre data-language="go">func Valid(data []byte) bool</pre> <p>Valid reports whether data is a valid JSON encoding. </p> <h4 id="example_Valid"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">goodJSON := `{"example": 1}`
badJSON := `{"example":2:]}}`
fmt.Println(json.Valid([]byte(goodJSON)), json.Valid([]byte(badJSON)))
</pre> <p>Output:</p> <pre class="output" data-language="go">true false
</pre> <h2 id="Decoder">type <span>Decoder</span> </h2> <p>A Decoder reads and decodes JSON values from an input stream. </p>
<pre data-language="go">type Decoder struct {
// contains filtered or unexported fields
}
</pre> <h4 id="example_Decoder"> <span class="text">Example</span>
</h4> <p>This example uses a Decoder to decode a stream of distinct JSON values. </p> <p>Code:</p> <pre class="code" data-language="go">const jsonStream = `
{"Name": "Ed", "Text": "Knock knock."}
{"Name": "Sam", "Text": "Who's there?"}
{"Name": "Ed", "Text": "Go fmt."}
{"Name": "Sam", "Text": "Go fmt who?"}
{"Name": "Ed", "Text": "Go fmt yourself!"}
`
type Message struct {
Name, Text string
}
dec := json.NewDecoder(strings.NewReader(jsonStream))
for {
var m Message
if err := dec.Decode(&m); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
fmt.Printf("%s: %s\n", m.Name, m.Text)
}
</pre> <p>Output:</p> <pre class="output" data-language="go">Ed: Knock knock.
Sam: Who's there?
Ed: Go fmt.
Sam: Go fmt who?
Ed: Go fmt yourself!
</pre> <h3 id="NewDecoder">func <span>NewDecoder</span> </h3> <pre data-language="go">func NewDecoder(r io.Reader) *Decoder</pre> <p>NewDecoder returns a new decoder that reads from r. </p>
<p>The decoder introduces its own buffering and may read data from r beyond the JSON values requested. </p>
<h3 id="Decoder.Buffered">func (*Decoder) <span>Buffered</span> <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (dec *Decoder) Buffered() io.Reader</pre> <p>Buffered returns a reader of the data remaining in the Decoder's buffer. The reader is valid until the next call to <a href="#Decoder.Decode">Decoder.Decode</a>. </p>
<h3 id="Decoder.Decode">func (*Decoder) <span>Decode</span> </h3> <pre data-language="go">func (dec *Decoder) Decode(v any) error</pre> <p>Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v. </p>
<p>See the documentation for <a href="#Unmarshal">Unmarshal</a> for details about the conversion of JSON into a Go value. </p> <h4 id="example_Decoder_Decode_stream"> <span class="text">Example (Stream)</span>
</h4> <p>This example uses a Decoder to decode a streaming array of JSON objects. </p> <p>Code:</p> <pre class="code" data-language="go">const jsonStream = `
[
{"Name": "Ed", "Text": "Knock knock."},
{"Name": "Sam", "Text": "Who's there?"},
{"Name": "Ed", "Text": "Go fmt."},
{"Name": "Sam", "Text": "Go fmt who?"},
{"Name": "Ed", "Text": "Go fmt yourself!"}
]
`
type Message struct {
Name, Text string
}
dec := json.NewDecoder(strings.NewReader(jsonStream))
// read open bracket
t, err := dec.Token()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%T: %v\n", t, t)
// while the array contains values
for dec.More() {
var m Message
// decode an array value (Message)
err := dec.Decode(&m)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%v: %v\n", m.Name, m.Text)
}
// read closing bracket
t, err = dec.Token()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%T: %v\n", t, t)
</pre> <p>Output:</p> <pre class="output" data-language="go">json.Delim: [
Ed: Knock knock.
Sam: Who's there?
Ed: Go fmt.
Sam: Go fmt who?
Ed: Go fmt yourself!
json.Delim: ]
</pre> <h3 id="Decoder.DisallowUnknownFields">func (*Decoder) <span>DisallowUnknownFields</span> <span title="Added in Go 1.10">1.10</span> </h3> <pre data-language="go">func (dec *Decoder) DisallowUnknownFields()</pre> <p>DisallowUnknownFields causes the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields in the destination. </p>
<h3 id="Decoder.InputOffset">func (*Decoder) <span>InputOffset</span> <span title="Added in Go 1.14">1.14</span> </h3> <pre data-language="go">func (dec *Decoder) InputOffset() int64</pre> <p>InputOffset returns the input stream byte offset of the current decoder position. The offset gives the location of the end of the most recently returned token and the beginning of the next token. </p>
<h3 id="Decoder.More">func (*Decoder) <span>More</span> <span title="Added in Go 1.5">1.5</span> </h3> <pre data-language="go">func (dec *Decoder) More() bool</pre> <p>More reports whether there is another element in the current array or object being parsed. </p>
<h3 id="Decoder.Token">func (*Decoder) <span>Token</span> <span title="Added in Go 1.5">1.5</span> </h3> <pre data-language="go">func (dec *Decoder) Token() (Token, error)</pre> <p>Token returns the next JSON token in the input stream. At the end of the input stream, Token returns nil, <span>io.EOF</span>. </p>
<p>Token guarantees that the delimiters [ ] { } it returns are properly nested and matched: if Token encounters an unexpected delimiter in the input, it will return an error. </p>
<p>The input stream consists of basic JSON values—bool, string, number, and null—along with delimiters [ ] { } of type <a href="#Delim">Delim</a> to mark the start and end of arrays and objects. Commas and colons are elided. </p> <h4 id="example_Decoder_Token"> <span class="text">Example</span>
</h4> <p>This example uses a Decoder to decode a stream of distinct JSON values. </p> <p>Code:</p> <pre class="code" data-language="go">const jsonStream = `
{"Message": "Hello", "Array": [1, 2, 3], "Null": null, "Number": 1.234}
`
dec := json.NewDecoder(strings.NewReader(jsonStream))
for {
t, err := dec.Token()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
fmt.Printf("%T: %v", t, t)
if dec.More() {
fmt.Printf(" (more)")
}
fmt.Printf("\n")
}
</pre> <p>Output:</p> <pre class="output" data-language="go">json.Delim: { (more)
string: Message (more)
string: Hello (more)
string: Array (more)
json.Delim: [ (more)
float64: 1 (more)
float64: 2 (more)
float64: 3
json.Delim: ] (more)
string: Null (more)
<nil>: <nil> (more)
string: Number (more)
float64: 1.234
json.Delim: }
</pre> <h3 id="Decoder.UseNumber">func (*Decoder) <span>UseNumber</span> <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (dec *Decoder) UseNumber()</pre> <p>UseNumber causes the Decoder to unmarshal a number into an interface{} as a <a href="#Number">Number</a> instead of as a float64. </p>
<h2 id="Delim">type <span>Delim</span> <span title="Added in Go 1.5">1.5</span> </h2> <p>A Delim is a JSON array or object delimiter, one of [ ] { or }. </p>
<pre data-language="go">type Delim rune</pre> <h3 id="Delim.String">func (Delim) <span>String</span> <span title="Added in Go 1.5">1.5</span> </h3> <pre data-language="go">func (d Delim) String() string</pre> <h2 id="Encoder">type <span>Encoder</span> </h2> <p>An Encoder writes JSON values to an output stream. </p>
<pre data-language="go">type Encoder struct {
// contains filtered or unexported fields
}
</pre> <h3 id="NewEncoder">func <span>NewEncoder</span> </h3> <pre data-language="go">func NewEncoder(w io.Writer) *Encoder</pre> <p>NewEncoder returns a new encoder that writes to w. </p>
<h3 id="Encoder.Encode">func (*Encoder) <span>Encode</span> </h3> <pre data-language="go">func (enc *Encoder) Encode(v any) error</pre> <p>Encode writes the JSON encoding of v to the stream, followed by a newline character. </p>
<p>See the documentation for <a href="#Marshal">Marshal</a> for details about the conversion of Go values to JSON. </p>
<h3 id="Encoder.SetEscapeHTML">func (*Encoder) <span>SetEscapeHTML</span> <span title="Added in Go 1.7">1.7</span> </h3> <pre data-language="go">func (enc *Encoder) SetEscapeHTML(on bool)</pre> <p>SetEscapeHTML specifies whether problematic HTML characters should be escaped inside JSON quoted strings. The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e to avoid certain safety problems that can arise when embedding JSON in HTML. </p>
<p>In non-HTML settings where the escaping interferes with the readability of the output, SetEscapeHTML(false) disables this behavior. </p>
<h3 id="Encoder.SetIndent">func (*Encoder) <span>SetIndent</span> <span title="Added in Go 1.7">1.7</span> </h3> <pre data-language="go">func (enc *Encoder) SetIndent(prefix, indent string)</pre> <p>SetIndent instructs the encoder to format each subsequent encoded value as if indented by the package-level function Indent(dst, src, prefix, indent). Calling SetIndent("", "") disables indentation. </p>
<h2 id="InvalidUTF8Error">type <span>InvalidUTF8Error</span> </h2> <p>Before Go 1.2, an InvalidUTF8Error was returned by <a href="#Marshal">Marshal</a> when attempting to encode a string value with invalid UTF-8 sequences. As of Go 1.2, <a href="#Marshal">Marshal</a> instead coerces the string to valid UTF-8 by replacing invalid bytes with the Unicode replacement rune U+FFFD. </p>
<p>Deprecated: No longer used; kept for compatibility. </p>
<pre data-language="go">type InvalidUTF8Error struct {
S string // the whole string value that caused the error
}
</pre> <h3 id="InvalidUTF8Error.Error">func (*InvalidUTF8Error) <span>Error</span> </h3> <pre data-language="go">func (e *InvalidUTF8Error) Error() string</pre> <h2 id="InvalidUnmarshalError">type <span>InvalidUnmarshalError</span> </h2> <p>An InvalidUnmarshalError describes an invalid argument passed to <a href="#Unmarshal">Unmarshal</a>. (The argument to <a href="#Unmarshal">Unmarshal</a> must be a non-nil pointer.) </p>
<pre data-language="go">type InvalidUnmarshalError struct {
Type reflect.Type
}
</pre> <h3 id="InvalidUnmarshalError.Error">func (*InvalidUnmarshalError) <span>Error</span> </h3> <pre data-language="go">func (e *InvalidUnmarshalError) Error() string</pre> <h2 id="Marshaler">type <span>Marshaler</span> </h2> <p>Marshaler is the interface implemented by types that can marshal themselves into valid JSON. </p>
<pre data-language="go">type Marshaler interface {
MarshalJSON() ([]byte, error)
}</pre> <h2 id="MarshalerError">type <span>MarshalerError</span> </h2> <p>A MarshalerError represents an error from calling a [Marshaler.MarshalJSON] or <span>encoding.TextMarshaler.MarshalText</span> method. </p>
<pre data-language="go">type MarshalerError struct {
Type reflect.Type
Err error
// contains filtered or unexported fields
}
</pre> <h3 id="MarshalerError.Error">func (*MarshalerError) <span>Error</span> </h3> <pre data-language="go">func (e *MarshalerError) Error() string</pre> <h3 id="MarshalerError.Unwrap">func (*MarshalerError) <span>Unwrap</span> <span title="Added in Go 1.13">1.13</span> </h3> <pre data-language="go">func (e *MarshalerError) Unwrap() error</pre> <p>Unwrap returns the underlying error. </p>
<h2 id="Number">type <span>Number</span> <span title="Added in Go 1.1">1.1</span> </h2> <p>A Number represents a JSON number literal. </p>
<pre data-language="go">type Number string</pre> <h3 id="Number.Float64">func (Number) <span>Float64</span> <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (n Number) Float64() (float64, error)</pre> <p>Float64 returns the number as a float64. </p>
<h3 id="Number.Int64">func (Number) <span>Int64</span> <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (n Number) Int64() (int64, error)</pre> <p>Int64 returns the number as an int64. </p>
<h3 id="Number.String">func (Number) <span>String</span> <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (n Number) String() string</pre> <p>String returns the literal text of the number. </p>
<h2 id="RawMessage">type <span>RawMessage</span> </h2> <p>RawMessage is a raw encoded JSON value. It implements <a href="#Marshaler">Marshaler</a> and <a href="#Unmarshaler">Unmarshaler</a> and can be used to delay JSON decoding or precompute a JSON encoding. </p>
<pre data-language="go">type RawMessage []byte</pre> <h4 id="example_RawMessage_marshal"> <span class="text">Example (Marshal)</span>
</h4> <p>This example uses RawMessage to use a precomputed JSON during marshal. </p> <p>Code:</p> <pre class="code" data-language="go">h := json.RawMessage(`{"precomputed": true}`)
c := struct {
Header *json.RawMessage `json:"header"`
Body string `json:"body"`
}{Header: &h, Body: "Hello Gophers!"}
b, err := json.MarshalIndent(&c, "", "\t")
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
</pre> <p>Output:</p> <pre class="output" data-language="go">{
"header": {
"precomputed": true
},
"body": "Hello Gophers!"
}
</pre> <h4 id="example_RawMessage_unmarshal"> <span class="text">Example (Unmarshal)</span>
</h4> <p>This example uses RawMessage to delay parsing part of a JSON message. </p> <p>Code:</p> <pre class="code" data-language="go">type Color struct {
Space string
Point json.RawMessage // delay parsing until we know the color space
}
type RGB struct {
R uint8
G uint8
B uint8
}
type YCbCr struct {
Y uint8
Cb int8
Cr int8
}
var j = []byte(`[
{"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}},
{"Space": "RGB", "Point": {"R": 98, "G": 218, "B": 255}}
]`)
var colors []Color
err := json.Unmarshal(j, &colors)
if err != nil {
log.Fatalln("error:", err)
}
for _, c := range colors {
var dst any
switch c.Space {
case "RGB":
dst = new(RGB)
case "YCbCr":
dst = new(YCbCr)
}
err := json.Unmarshal(c.Point, dst)
if err != nil {
log.Fatalln("error:", err)
}
fmt.Println(c.Space, dst)
}
</pre> <p>Output:</p> <pre class="output" data-language="go">YCbCr &{255 0 -10}
RGB &{98 218 255}
</pre> <h3 id="RawMessage.MarshalJSON">func (RawMessage) <span>MarshalJSON</span> <span title="Added in Go 1.8">1.8</span> </h3> <pre data-language="go">func (m RawMessage) MarshalJSON() ([]byte, error)</pre> <p>MarshalJSON returns m as the JSON encoding of m. </p>
<h3 id="RawMessage.UnmarshalJSON">func (*RawMessage) <span>UnmarshalJSON</span> </h3> <pre data-language="go">func (m *RawMessage) UnmarshalJSON(data []byte) error</pre> <p>UnmarshalJSON sets *m to a copy of data. </p>
<h2 id="SyntaxError">type <span>SyntaxError</span> </h2> <p>A SyntaxError is a description of a JSON syntax error. <a href="#Unmarshal">Unmarshal</a> will return a SyntaxError if the JSON can't be parsed. </p>
<pre data-language="go">type SyntaxError struct {
Offset int64 // error occurred after reading Offset bytes
// contains filtered or unexported fields
}
</pre> <h3 id="SyntaxError.Error">func (*SyntaxError) <span>Error</span> </h3> <pre data-language="go">func (e *SyntaxError) Error() string</pre> <h2 id="Token">type <span>Token</span> <span title="Added in Go 1.5">1.5</span> </h2> <p>A Token holds a value of one of these types: </p>
<ul> <li>
<a href="#Delim">Delim</a>, for the four JSON delimiters [ ] { } </li>
<li>bool, for JSON booleans </li>
<li>float64, for JSON numbers </li>
<li>
<a href="#Number">Number</a>, for JSON numbers </li>
<li>string, for JSON string literals </li>
<li>nil, for JSON null </li>
</ul> <pre data-language="go">type Token any</pre> <h2 id="UnmarshalFieldError">type <span>UnmarshalFieldError</span> </h2> <p>An UnmarshalFieldError describes a JSON object key that led to an unexported (and therefore unwritable) struct field. </p>
<p>Deprecated: No longer used; kept for compatibility. </p>
<pre data-language="go">type UnmarshalFieldError struct {
Key string
Type reflect.Type
Field reflect.StructField
}
</pre> <h3 id="UnmarshalFieldError.Error">func (*UnmarshalFieldError) <span>Error</span> </h3> <pre data-language="go">func (e *UnmarshalFieldError) Error() string</pre> <h2 id="UnmarshalTypeError">type <span>UnmarshalTypeError</span> </h2> <p>An UnmarshalTypeError describes a JSON value that was not appropriate for a value of a specific Go type. </p>
<pre data-language="go">type UnmarshalTypeError struct {
Value string // description of JSON value - "bool", "array", "number -5"
Type reflect.Type // type of Go value it could not be assigned to
Offset int64 // error occurred after reading Offset bytes; added in Go 1.5
Struct string // name of the struct type containing the field; added in Go 1.8
Field string // the full path from root node to the field; added in Go 1.8
}
</pre> <h3 id="UnmarshalTypeError.Error">func (*UnmarshalTypeError) <span>Error</span> </h3> <pre data-language="go">func (e *UnmarshalTypeError) Error() string</pre> <h2 id="Unmarshaler">type <span>Unmarshaler</span> </h2> <p>Unmarshaler is the interface implemented by types that can unmarshal a JSON description of themselves. The input can be assumed to be a valid encoding of a JSON value. UnmarshalJSON must copy the JSON data if it wishes to retain the data after returning. </p>
<p>By convention, to approximate the behavior of <a href="#Unmarshal">Unmarshal</a> itself, Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op. </p>
<pre data-language="go">type Unmarshaler interface {
UnmarshalJSON([]byte) error
}</pre> <h2 id="UnsupportedTypeError">type <span>UnsupportedTypeError</span> </h2> <p>An UnsupportedTypeError is returned by <a href="#Marshal">Marshal</a> when attempting to encode an unsupported value type. </p>
<pre data-language="go">type UnsupportedTypeError struct {
Type reflect.Type
}
</pre> <h3 id="UnsupportedTypeError.Error">func (*UnsupportedTypeError) <span>Error</span> </h3> <pre data-language="go">func (e *UnsupportedTypeError) Error() string</pre> <h2 id="UnsupportedValueError">type <span>UnsupportedValueError</span> </h2> <p>An UnsupportedValueError is returned by <a href="#Marshal">Marshal</a> when attempting to encode an unsupported value. </p>
<pre data-language="go">type UnsupportedValueError struct {
Value reflect.Value
Str string
}
</pre> <h3 id="UnsupportedValueError.Error">func (*UnsupportedValueError) <span>Error</span> </h3> <pre data-language="go">func (e *UnsupportedValueError) Error() string</pre><div class="_attribution">
<p class="_attribution-p">
© Google, Inc.<br>Licensed under the Creative Commons Attribution License 3.0.<br>
<a href="http://golang.org/pkg/encoding/json/" class="_attribution-link">http://golang.org/pkg/encoding/json/</a>
</p>
</div>
|