json - 从 json post 请求中转义 html

标签 json go escaping go-templates

我想将请求中的一些 json 转换为 html,但它不起作用,解码 json 时出现错误

import (
    "html/template" 
    "encoding/json"
    "net/http"
    "io"
    "io/ioutil"
    "log"
)

func anyFunction(w http.ResponseWriter, r *http.Request) {
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        log.Print(err)
    }
    ri, wo := io.Pipe()
    go template.HTMLEscape(wo, body)   
    var t []customStruct
    json.NewDecoder(ri).Decode(t) //error: Invalid character:'&' looking for beginning of object key string
    ...
}

来自客户端的 json 是有效的,因为我使用的是“JSON.stringify(data)” 去 1.9.4

最佳答案

不要对整个有效的 json 负载进行 html 转义,您会无意中使其无效,从而导致 json 解码失败。

如果您需要清理包含在 有效 json 中的值,您可以在首次解码之后执行此操作,也可以在解码期间通过实现 json.Unmarshaler 执行此操作自定义类型上的接口(interface),然后可以清理值的原始字节。

关于json - 从 json post 请求中转义 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49288607/

相关文章:

javascript - AngularJS - 将登录用户与 JSON 数组中的用户匹配

javascript - 使用 node.js 驱动程序将 Mongo 集合导出到 json

戈朗 : How can i access json decoded field?

bash - 在 shell 脚本中传递 CMAKE_CXX_FLAGS

php - json_decode() 返回错误 "Notice: Trying to get property of non-object"

SQL Server 2016 EscapeCharacter 问题

arrays - 如何将 Go validator.FieldLevel.Field() 转换为字符串数组

go - 如何构建 go 命令的内部结构

c# - 如何强制 Console.WriteLine() 逐字打印字符串?

lua - Lua 中用单反斜杠替换输入中的双反斜杠