golang - 显示字符,而不是ascii。喜欢'&',而不是'\0026' [英] golang - display character, not ascii. Like '&', not '\0026'

查看:568
本文介绍了golang - 显示字符,而不是ascii。喜欢'&',而不是'\0026'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的测试代码。只需一个简单的http服务器。然后生成一个值为&的json数据。但结果是我不想要的。结果是在代码块下面。

This is my testing code.Just make a simple http server. Then generating a json data that it's value 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:\\\&}

&

控制台还显示:

{key :\\\&}

&

& 不在json时,浏览器和控制台将打印& '。

When '&' not in json, browser and console will print '&'.

推荐答案

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
)

type Search struct {
    Query string `json:"query"`
}

func main() {
    data := &Search{Query: "http://google.com/?q=stackoverflow&ie=UTF-8"}
    responseJSON, _ := JSONMarshal(data, true)
    fmt.Println(string(responseJSON))

}

func JSONMarshal(v interface{}, safeEncoding bool) ([]byte, error) {
    b, err := json.Marshal(v)

    if safeEncoding {
        b = bytes.Replace(b, []byte("\\u003c"), []byte("<"), -1)
        b = bytes.Replace(b, []byte("\\u003e"), []byte(">"), -1)
        b = bytes.Replace(b, []byte("\\u0026"), []byte("&"), -1)
    }
    return b, err
}

结果:

JSONMarshal(data, true)
{"query":"http://google.com/?q=stackoverflow&ie=UTF-8"}

JSONMarshal(data, false)
{"query":"http://google.com/?q=stackoverflow\u0026ie=UTF-8"}

https://github.com/clbanning/mxj/blob/master/ json.go#L20

Playbook: http://play.golang.org/p/c7M32gICl8

Playbook: http://play.golang.org/p/c7M32gICl8

这篇关于golang - 显示字符,而不是ascii。喜欢'&amp;',而不是'\0026'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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