json - JSON 模板中的转义值

标签 json templates go escaping go-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 中不支持“//”注释。

关于json - JSON 模板中的转义值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54250532/

相关文章:

go - 从 Golang 映射中读取字符串

oop - 如何处理多态对象

c++ - 命名模板参数是在最新标准中还是在现代编译器中实现的?

javascript - 带过滤器的 Vue JS axios 请求 - this.XX.filter 不是函数

javascript - 通过 AJAX 加载 jqPlot

javascript - 如何让 Backbone.ajax 成功返回数据

c++ - 获得通用引用的优势,无需通用引用

C++ list<T>::iterator 不能在派生类模板中使用

Golang 和 JWT - 简单注销

javascript - 让 Discord Bot 链接另一个 channel