Debian Codegraph @

pkg/internal/third_party/go-json-experiment/json/jsontext/example_test.go

raw
1 // Copyright 2023 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
5 package jsontext_test
6
7 import (
8 "bytes"
9 "fmt"
10 "io"
11 "log"
12 "strings"
13
14 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json"
15 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext"
16 )
17
18 // This example demonstrates the use of the [Encoder] and [Decoder] to
19 // parse and modify JSON without unmarshaling it into a concrete Go type.
20 func Example_stringReplace() {
21 // Example input with non-idiomatic use of "Golang" instead of "Go".
22 const input = `{
23 "title": "Golang version 1 is released",
24 "author": "Andrew Gerrand",
25 "date": "2012-03-28",
26 "text": "Today marks a major milestone in the development of the Golang programming language.",
27 "otherArticles": [
28 "Twelve Years of Golang",
29 "The Laws of Reflection",
30 "Learn Golang from your browser"
31 ]
32 }`
33
34 // Using a Decoder and Encoder, we can parse through every token,
35 // check and modify the token if necessary, and
36 // write the token to the output.
37 var replacements []jsontext.Pointer
38 in := strings.NewReader(input)
39 dec := jsontext.NewDecoder(in)
40 out := new(bytes.Buffer)
41 enc := jsontext.NewEncoder(out, jsontext.Multiline(true)) // expand for readability
42 for {
43 // Read a token from the input.
44 tok, err := dec.ReadToken()
45 if err != nil {
46 if err == io.EOF {
47 break
48 }
49 log.Fatal(err)
50 }
51
52 // Check whether the token contains the string "Golang" and
53 // replace each occurrence with "Go" instead.
54 if tok.Kind() == '"' && strings.Contains(tok.String(), "Golang") {
55 replacements = append(replacements, dec.StackPointer())
56 tok = jsontext.String(strings.ReplaceAll(tok.String(), "Golang", "Go"))
57 }
58
59 // Write the (possibly modified) token to the output.
60 if err := enc.WriteToken(tok); err != nil {
61 log.Fatal(err)
62 }
63 }
64
65 // Print the list of replacements and the adjusted JSON output.
66 if len(replacements) > 0 {
67 fmt.Println(`Replaced "Golang" with "Go" in:`)
68 for _, where := range replacements {
69 fmt.Println("\t" + where)
70 }
71 fmt.Println()
72 }
73 fmt.Println("Result:", out.String())
74
75 // Output:
76 // Replaced "Golang" with "Go" in:
77 // /title
78 // /text
79 // /otherArticles/0
80 // /otherArticles/2
81 //
82 // Result: {
83 // "title": "Go version 1 is released",
84 // "author": "Andrew Gerrand",
85 // "date": "2012-03-28",
86 // "text": "Today marks a major milestone in the development of the Go programming language.",
87 // "otherArticles": [
88 // "Twelve Years of Go",
89 // "The Laws of Reflection",
90 // "Learn Go from your browser"
91 // ]
92 // }
93 }
94
95 // Directly embedding JSON within HTML requires special handling for safety.
96 // Escape certain runes to prevent JSON directly treated as HTML
97 // from being able to perform <script> injection.
98 //
99 // This example shows how to obtain equivalent behavior provided by the
100 // v1 [encoding/json] package that is no longer directly supported by this package.
101 // Newly written code that intermix JSON and HTML should instead be using the
102 // [github.com/google/safehtml] module for safety purposes.
103 func ExampleEscapeForHTML() {
104 page := struct {
105 Title string
106 Body string
107 }{
108 Title: "Example Embedded Javascript",
109 Body: `<script> console.log("Hello, world!"); </script>`,
110 }
111
112 b, err := json.Marshal(&page,
113 // Escape certain runes within a JSON string so that
114 // JSON will be safe to directly embed inside HTML.
115 jsontext.EscapeForHTML(true),
116 jsontext.EscapeForJS(true),
117 jsontext.Multiline(true)) // expand for readability
118 if err != nil {
119 log.Fatal(err)
120 }
121 fmt.Println(string(b))
122
123 // Output:
124 // {
125 // "Title": "Example Embedded Javascript",
126 // "Body": "\u003cscript\u003e console.log(\"Hello, world!\"); \u003c/script\u003e"
127 // }
128 }