Source file
src/encoding/json/v2/example_format_test.go
1
2
3
4
5
6
7 package json_test
8
9 import (
10 "encoding/json/jsontext"
11 "encoding/json/v2"
12 "fmt"
13 "log"
14 "math"
15 "time"
16 )
17
18
19 func Example_formatFlags() {
20 value := struct {
21 BytesBase64 []byte `json:",format:base64"`
22 BytesHex [8]byte `json:",format:hex"`
23 BytesArray []byte `json:",format:array"`
24 FloatNonFinite float64 `json:",format:nonfinite"`
25 MapEmitNull map[string]any `json:",format:emitnull"`
26 SliceEmitNull []any `json:",format:emitnull"`
27 TimeDateOnly time.Time `json:",format:'2006-01-02'"`
28 TimeUnixSec time.Time `json:",format:unix"`
29 DurationSecs time.Duration `json:",format:sec"`
30 DurationNanos time.Duration `json:",format:nano"`
31 DurationISO8601 time.Duration `json:",format:iso8601"`
32 }{
33 BytesBase64: []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
34 BytesHex: [8]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
35 BytesArray: []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
36 FloatNonFinite: math.NaN(),
37 MapEmitNull: nil,
38 SliceEmitNull: nil,
39 TimeDateOnly: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC),
40 TimeUnixSec: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC),
41 DurationSecs: 12*time.Hour + 34*time.Minute + 56*time.Second + 7*time.Millisecond + 8*time.Microsecond + 9*time.Nanosecond,
42 DurationNanos: 12*time.Hour + 34*time.Minute + 56*time.Second + 7*time.Millisecond + 8*time.Microsecond + 9*time.Nanosecond,
43 DurationISO8601: 12*time.Hour + 34*time.Minute + 56*time.Second + 7*time.Millisecond + 8*time.Microsecond + 9*time.Nanosecond,
44 }
45
46 b, err := json.Marshal(&value)
47 if err != nil {
48 log.Fatal(err)
49 }
50 (*jsontext.Value)(&b).Indent()
51 fmt.Println(string(b))
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
View as plain text