用于html/template創(chuàng)建 JSON 輸出。代碼片段如下(playground):package mainimport ( "bytes" "encoding/json" "fmt" "html/template")const tpl = `{ "key": "{{- .Value -}}" // Replace with js .Value to get another error}`func main() { t, err := template.New("").Parse(tpl) if err != nil { panic(err) } var buf bytes.Buffer err = t.Execute(&buf, struct{ Value string }{"Test\\ > \\ Value"}) if err != nil { panic(err) } data := make(map[string]string) err = json.Unmarshal(buf.Bytes(), &data) if err != nil { panic(err) } fmt.Printf("%v\n", data)}如果我嘗試.Value按原樣插入 - 則會出現(xiàn)以下錯誤:恐慌:字符串轉(zhuǎn)義代碼中的無效字符“”這是因為在 JSON 中變成\\了不正確的轉(zhuǎn)義。我可以通過向模板添加函數(shù)來解決這個問題:\\ + spacejsconst tpl = `
{
"key": "{{- js .Value -}}"
}
`在這種情況下,它會因另一個錯誤而失?。嚎只牛鹤址D(zhuǎn)義代碼中的無效字符“x”這是因為js函數(shù)將>sign轉(zhuǎn)換\x3c為\xJSON 中的轉(zhuǎn)義不正確。任何想法如何獲得正確轉(zhuǎn)義 JSON 字符串的通用函數(shù)?考慮到所有這些困難,是否有替代方法(例如外部庫)來創(chuàng)建 JSON 模板?
1 回答

largeQ
TA貢獻2039條經(jīng)驗 獲得超8個贊
選項 0
https://play.golang.org/p/4DMTAfEapbM
正如@Adrian
建議的那樣,使用text/template
,所以我們只需要一個unescape
和結(jié)尾。
選項1
https://play.golang.org/p/oPC1E6s-EwB
在執(zhí)行模板之前進行轉(zhuǎn)義,然后在需要字符串值時取消轉(zhuǎn)義兩次。
選項 2
https://play.golang.org/p/zD-cTO07GZq
將“ \\
”替換為“ \\\\
”。
}{"Test\\ > \\ Value"}) to }{"Test\\\\ > \\\\ Value"})
多一個
中不支持“//”注釋json
。
- 1 回答
- 0 關(guān)注
- 160 瀏覽
添加回答
舉報
0/150
提交
取消