1
2
3
4
5
6
7 package jsontext_test
8
9 import (
10 "bytes"
11 "fmt"
12 "io"
13 "log"
14 "strings"
15
16 "encoding/json/jsontext"
17 "encoding/json/v2"
18 )
19
20
21
22 func Example_stringReplace() {
23
24 const input = `{
25 "title": "Golang version 1 is released",
26 "author": "Andrew Gerrand",
27 "date": "2012-03-28",
28 "text": "Today marks a major milestone in the development of the Golang programming language.",
29 "otherArticles": [
30 "Twelve Years of Golang",
31 "The Laws of Reflection",
32 "Learn Golang from your browser"
33 ]
34 }`
35
36
37
38
39 var replacements []jsontext.Pointer
40 in := strings.NewReader(input)
41 dec := jsontext.NewDecoder(in)
42 out := new(bytes.Buffer)
43 enc := jsontext.NewEncoder(out, jsontext.Multiline(true))
44 for {
45
46 tok, err := dec.ReadToken()
47 if err != nil {
48 if err == io.EOF {
49 break
50 }
51 log.Fatal(err)
52 }
53
54
55
56 if tok.Kind() == '"' && strings.Contains(tok.String(), "Golang") {
57 replacements = append(replacements, dec.StackPointer())
58 tok = jsontext.String(strings.ReplaceAll(tok.String(), "Golang", "Go"))
59 }
60
61
62 if err := enc.WriteToken(tok); err != nil {
63 log.Fatal(err)
64 }
65 }
66
67
68 if len(replacements) > 0 {
69 fmt.Println(`Replaced "Golang" with "Go" in:`)
70 for _, where := range replacements {
71 fmt.Println("\t" + where)
72 }
73 fmt.Println()
74 }
75 fmt.Println("Result:", out.String())
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 func ExampleEscapeForHTML() {
106 page := struct {
107 Title string
108 Body string
109 }{
110 Title: "Example Embedded Javascript",
111 Body: `<script> console.log("Hello, world!"); </script>`,
112 }
113
114 b, err := json.Marshal(&page,
115
116
117 jsontext.EscapeForHTML(true),
118 jsontext.EscapeForJS(true),
119 jsontext.Multiline(true))
120 if err != nil {
121 log.Fatal(err)
122 }
123 fmt.Println(string(b))
124
125
126
127
128
129
130 }
131
132 func ExampleMultiline() {
133 type Pet struct {
134 Name string
135 Species string
136 Breed string
137 }
138
139 p := Pet{
140 Name: "Oliver",
141 Species: "Dog",
142 Breed: "Goldendoodle",
143 }
144
145 b, err := json.Marshal(p, jsontext.Multiline(true))
146 if err != nil {
147 log.Fatal(err)
148 }
149
150 fmt.Println(string(b))
151
152
153
154
155
156
157 }
158
View as plain text