1 回答

TA貢獻1811條經驗 獲得超5個贊
在Marshal
json 包的文檔中https://pkg.go.dev/encoding/json#Marshal你會發現以下段落:
字符串值編碼為強制為有效 UTF-8 的 JSON 字符串,用 Unicode 替換符文替換無效字節。為了將 JSON 安全地嵌入到 HTML 標簽中,字符串使用 HTMLEscape 編碼,它替換了“<”、“>”、“&”,U+2028 和 U+2029 被轉義為“\u003c”, “\u003e”、“\u0026”、“\u2028”和“\u2029”。使用編碼器時,可以通過調用 SetEscapeHTML(false) 禁用此替換。
因此,請嘗試使用Encoder
, 示例:
package main
import (
"bytes"
"encoding/json"
"fmt"
)
type Foo struct {
Name string
Surname string
Likes map[string]interface{}
Hates map[string]interface{}
newGuy bool //rpcclonable
}
func main() {
foo := &Foo{
Name: "George",
Surname: "Denkin",
Likes: map[string]interface{}{
"Sports": "volleyball",
"Message": "<Geroge> play volleyball <usually>",
},
}
buf := &bytes.Buffer{} // or &strings.Builder{} as from the example of @mkopriva
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
err := enc.Encode(foo)
if err != nil {
return
}
fmt.Println(buf.String())
}
- 1 回答
- 0 關注
- 174 瀏覽
添加回答
舉報