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

如何在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 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,