1 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超5個贊
在Marshal
json 包的文檔中https://pkg.go.dev/encoding/json#Marshal你會發(fā)現(xiàn)以下段落:
字符串值編碼為強(qiáng)制為有效 UTF-8 的 JSON 字符串,用 Unicode 替換符文替換無效字節(jié)。為了將 JSON 安全地嵌入到 HTML 標(biāo)簽中,字符串使用 HTMLEscape 編碼,它替換了“<”、“>”、“&”,U+2028 和 U+2029 被轉(zhuǎn)義為“\u003c”, “\u003e”、“\u0026”、“\u2028”和“\u2029”。使用編碼器時,可以通過調(diào)用 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 關(guān)注
- 170 瀏覽
添加回答
舉報