dongliang2058 2017-08-28 08:34
浏览 1613
已采纳

如何在Golang的RESTful API中返回不带转义字符串的Json数据

I have written an API with Golang. This API does receive data from other services then it responses to users in type of JSON string. Here is the problems I got.

type message struct {
    Data string `json:"data"`
}

func test(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    data := // Retrieve message that contain backslash
    json.NewEncoder(w).Encode(message{Data: data})
}

` If there is a backslash in data that receive from other API. This API will send the response with double backslashes.

Example.

Received data: "asdasdasd\asdasdasd"

Response data: {"data": "asdasdasd\\asdasdasd"}

I have try to figure this out. Here what I got. All of this will be fine if I try to print out in the screen by using fmt.Println().

I only get problem when I try to send those out put in JSON string. Therefore, is there any way to send those data without double backslashes?

  • 写回答

2条回答 默认 最新

  • duancan1950 2017-08-28 09:01
    关注

    You can create a custom method and replace double backslashes with a single one.
    Something like that:

    func JSONMarshal(v interface{}, backslashEscape bool) ([]byte, error) {
        b, err := json.Marshal(v)
    
        if backslashEscape {
            b = bytes.Replace(b, []byte(`\\`), []byte(`\`), -1)
        }
        return b, err
    }
    

    The json/encoder packages has also DisableHTMLEscaping, if set to true, default is false, it allows you to escape HTML chars.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件