用于html/template创建 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按原样插入 - 则会出现以下错误:恐慌:字符串转义代码中的无效字符“”这是因为在 JSON 中变成\\了不正确的转义。我可以通过向模板添加函数来解决这个问题:\\ + spacejsconst tpl = `
{
"key": "{{- js .Value -}}"
}
`在这种情况下,它会因另一个错误而失败:恐慌:字符串转义代码中的无效字符“x”这是因为js函数将>sign转换\x3c为\xJSON 中的转义不正确。任何想法如何获得正确转义 JSON 字符串的通用函数?考虑到所有这些困难,是否有替代方法(例如外部库)来创建 JSON 模板?
1 回答
largeQ
TA贡献2039条经验 获得超7个赞
选项 0
https://play.golang.org/p/4DMTAfEapbM
正如@Adrian
建议的那样,使用text/template
,所以我们只需要一个unescape
和结尾。
选项1
https://play.golang.org/p/oPC1E6s-EwB
在执行模板之前进行转义,然后在需要字符串值时取消转义两次。
选项 2
https://play.golang.org/p/zD-cTO07GZq
将“ \\
”替换为“ \\\\
”。
}{"Test\\ > \\ Value"}) to }{"Test\\\\ > \\\\ Value"})
多一个
中不支持“//”注释json
。
- 1 回答
- 0 关注
- 131 浏览
添加回答
举报
0/150
提交
取消