在 JSON 个模板中转义值
Escaping values in JSON templates
使用 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
- 然后我收到以下错误:
panic: invalid character ' ' in string escape code
这是因为 \
变成了 \
而 \ + space
在 JSON 中是不正确的转义。我可以通过向模板添加 js
函数来解决此问题:
const tpl = `
{
"key": "{{- js .Value -}}"
}
`
在那种情况下它会失败并出现另一个错误:
panic: invalid character 'x' in string escape code
这是因为 js
函数将 >
符号转换为 \x3c
而 \x
在 JSON.
中是不正确的转义
关于如何获得可以正确转义 JSON 字符串的通用函数的任何想法?考虑到所有这些困难,是否有替代方法(例如外部库)来创建 JSON 模板?
选项 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
中不受支持。
使用 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
- 然后我收到以下错误:
panic: invalid character ' ' in string escape code
这是因为 \
变成了 \
而 \ + space
在 JSON 中是不正确的转义。我可以通过向模板添加 js
函数来解决此问题:
const tpl = `
{
"key": "{{- js .Value -}}"
}
`
在那种情况下它会失败并出现另一个错误:
panic: invalid character 'x' in string escape code
这是因为 js
函数将 >
符号转换为 \x3c
而 \x
在 JSON.
关于如何获得可以正确转义 JSON 字符串的通用函数的任何想法?考虑到所有这些困难,是否有替代方法(例如外部库)来创建 JSON 模板?
选项 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
中不受支持。