dongre9937 2013-01-28 17:08
浏览 563
已采纳

如何在Go中打印出JSON

I'm new to Go, and having trouble figuring out how to print out a JSON I've created. I'm using "encoding/json" and am getting a []byte returned. However when I go to print this out I get:

cannot use json_msg (type []byte) as type string in function argument

After receiving this I've tried to convert the []byte array to a string or an empty interface. However I can't seem to get it to work. Any ideas? Relevant code below:

type Message struct {
    Id int
    Name string
}



for _, row := range rows {
    m := Message{row.Int(0), row.Str(1)}

    json_msg, err := json.Marshal(m)

    if err == nil {
        panic(err)
    }//if

            //tried below to print out a interface, didn't work either
    //var f interface{}
    //err = json.Unmarshal(json_msg, &f)

    fmt.Fprintf(c.ResponseWriter, json_msg)
}//for
  • 写回答

3条回答 默认 最新

  • douduonang3169 2013-01-28 21:42
    关注

    there's a handful of ways to get what you're looking for.

    First, to answer your question directly, fmt.Fprintf if of type func(io.Writer, string, ...interface{}). Since you're passing c.ResponseWriter into it, I assume that's something that satisfies io.Writer. The second argument to fmt.Fprintf is a format string. If you want to print something as a string, you use the %s format string, so what you would want is this:

    fmt.Fprintf(c.ResponseWriter, "%s", json_msg)
    

    that answers your question directly, but let's go a little further: is that the right way to solve the problem you're solving? No, not really; it's a little weird to do it that way.

    First off, because we know that fmt.Fprintf accepts io.Writer, we're talking about something with a method of the form Write([]byte) (int, error). You could just write that []byte data to the ResponseWriter by calling the Write() method on the ResponseWriter directly:

    _, err := c.ResponseWriter.Write(json_msg)
    

    that's slightly less awkward. It turns out, there's an even better way to do this: use a json.Encoder. A json.Encoder is a struct that embeds an io.Writer, effectively adding to any io.Writer struct an Encode method, which will encode structs to json and write them to the writer. The difference is that what you're doing encodes the data to a byte slice in memory, and then copies that into an io.Writer, when you could just write it directly, like this:

    err := json.NewEncoder(c.ResponseWriter).Encode(m)
    

    and now you don't even have that intermediate []byte format.

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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?