如何显示字符而不是ASCII? [英] How to display a character instead of ascii?

查看:104
本文介绍了如何显示字符而不是ASCII?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的测试代码.只需制作一个简单的HTTP服务器即可.然后生成其值为&"的JSON数据.但是结果就是我不想要的.结果在代码块下方.

This is my testing code. Just make a simple HTTP server. Then generating a JSON data that it values is "&". But the result is what I don't want. The result is below the code block.

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

func testFunc(w http.ResponseWriter, r *http.Request) {
    data := make(map[string]string)
    data["key"] = "&"
    bytes, err := json.Marshal(data)
    if err != nil {
        fmt.Fprintln(w, "generator json error")
    } else {
        //print console
        fmt.Println(string(bytes))
        fmt.Println("&")
        //print broswer
        fmt.Fprintln(w, string(bytes))
        fmt.Fprintln(w, "&")
    }
}

func main() {
    http.HandleFunc("/", testFunc)
    err := http.ListenAndServe(":9090", nil)
    if err != nil {
        log.Fatal("ListenAndServe", err)
    }

}

结果: Chrome浏览器显示:

result: Chrome browser show:

{"key":"\u0026"}
&

控制台也显示:

{"key":"\u0026"}
&

&不在JSON中时,浏览器和控制台将打印&.

When & not in JSON, browser and console will print &.

推荐答案

在Go1.7中,他们拥有添加了一个新选项来解决此问题:

In Go1.7 they have added a new option to fix this:

encoding/json: add Encoder.DisableHTMLEscaping这提供了一种禁用<,>和&的转义的方法. JSON字符串中.

encoding/json: add Encoder.DisableHTMLEscaping This provides a way to disable the escaping of <, >, and & in JSON strings.

相关功能是

func (*Encoder) SetEscapeHTML

应将其应用于编码器.

enc := json.NewEncoder(os.Stdout)
enc.SetEscapeHTML(false)

修改了stupidbodo的示例: https://play.golang.org/p/HnWGJAjqPA

The example of stupidbodo modified: https://play.golang.org/p/HnWGJAjqPA

这篇关于如何显示字符而不是ASCII?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆