【问题标题】:Go template HTMLEscape json data and it show """ issue转到模板 HTMLEscape json 数据并显示“””问题
【发布时间】:2019-07-18 01:53:23
【问题描述】:

我尝试将 json 数据放到网络上,我使用json.Marshal 创建 json 数据。

流图为fmt.Println(string(jsonOut))结果

我使用template.HTMLEscape(w, []byte(jsonOut))在网页上显示,它会显示如下图。

" 变为 &#34

为什么会显示&#34,我该怎么做才能显示"

【问题讨论】:

  • 尽量不要打电话给template.HTMLEscape
  • @zzn 如果我不调用 template.HTMLEscape 我应该调用什么来在 web 中显示 json 数据?

标签: json go html-escape-characters html-escape


【解决方案1】:

如果你只想在 http 响应中显示 json

w.Write(jsonOut)

如果你想在html中显示json

t, _ := template.New("foo").Parse(`<head></head><body>{{$.data}}</body>`)   
_ = t.Execute(w, map[string]string{
    "data": string(jsonOut),
})

【讨论】:

    【解决方案2】:

    template.HTMLEscape 将转义特殊字符。

    使用以下代码可以将json数据发布到网络

    w.Header().Set("Content-Type", "application/json")
    w.Write(jsonOut)
    

    参考 https://www.alexedwards.net/blog/golang-response-snippets#json

    【讨论】:

      猜你喜欢
      • 2019-06-27
      • 2021-10-08
      • 2013-04-11
      • 2014-11-12
      • 2016-11-27
      • 1970-01-01
      • 2013-05-27
      • 2019-09-09
      • 2018-09-17
      相关资源
      最近更新 更多