【发布时间】:2018-05-24 04:15:38
【问题描述】:
我正在使用 go 和 beego 构建微服务应用程序。我正在尝试将 JSON 响应从服务 A 传递到服务 B,如下所示:
func (u *ServiceController) GetAll() {
req := httplib.Get("http://localhost/api/1/services")
str, err := req.String()
// str = {"id":1, "name":"some service"}
if err != nil {
fmt.Println(err)
}
u.Data["json"] = str
u.ServeJSON()
}
但是,当我发送响应时,我实际上是双重 json 编码:
"{\"id\":\"1\",\"name\":\"some service\"}"
最后,这是我想出的解决方案:
func (u *ServiceController) GetAll() {
req := httplib.Get("http://localhost/api/1/services")
str, err := req.String()
if err != nil {
fmt.Println(err)
}
strToByte := []byte(str)
u.Ctx.Output.Header("Content-Type", "application/json")
u.Ctx.Output.Body(strToByte)
}
【问题讨论】:
-
我要动态解析json。
-
如链接中所述
ServeJSON“JSONifies”您设置为Data["json"]的值,这意味着无论字符串的内容如何,一个字符串都会变成有效的 json 字符串,这就是它逃脱的原因。ServeJSON不适用于包含 json 的字符串。 -
如果您想发送包含有效 json 的字符串,您可以使用
u.Ctx.Output.Body(bytes []byte),使用[]byte(str)将您的字符串转换为字节。您还需要设置 HTTP 标头 Content-Type,您可以这样做:u.Ctx.Output.Header("Content-Type", "application/json")。 -
在 JS 中我会事先将 JSON 解析为 JS 对象,那么我应该怎么做呢?