用于html/template创建 JSON 输出。代码片段如下(playground):
package main
import (
"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按原样插入 - 则会出现以下错误:
恐慌:字符串转义代码中的无效字符“”
这是因为在 JSON 中变成\\了不正确的转义。我可以通过向模板添加函数来解决这个问题:\\ + spacejs
const tpl = `
{
"key": "{{- js .Value -}}"
}
`在这种情况下,它会因另一个错误而失败:
恐慌:字符串转义代码中的无效字符“x”
这是因为js函数将>sign转换\x3c为\xJSON 中的转义不正确。
任何想法如何获得正确转义 JSON 字符串的通用函数?考虑到所有这些困难,是否有替代方法(例如外部库)来创建 JSON 模板?
largeQ
相关分类