如何在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
dsdf64562672
dsdf64562672 c.ResponseWriter的“c”从哪里来?
一年多之前 回复

3个回答



有几种方法可以获取您想要的东西。</ p>

首先, 如果类型为 func(io.Writer,string,... interface {})</ code>,则直接回答您的问题, fmt.Fprintf </ code>。 由于您要向其中传递 c.ResponseWriter </ code>,因此我认为这可以满足 io.Writer </ code>。 fmt.Fprintf </ code>的第二个参数是格式字符串。 如果要将某些内容打印为字符串,请使用%s </ code>格式的字符串,因此您需要的是:</ p>

  fmt.Fprintf  (c.ResponseWriter,“%s”,json_msg)
</ code> </ pre>

,它可以直接回答您的问题,但让我们进一步介绍一下:这是解决问题的正确方法 您正在解决的问题? 不,不是真的; </ p>

首先,因为我们知道 fmt.Fprintf </ code>接受 io.Writer </ code>, 我们正在谈论一种形式为 Write([] byte)(int,error)</ code>的方法。 您可以通过在 ResponseWriter </ code>上调用 Write()</ code>方法,将 [] byte </ code>数据写入 ResponseWriter </ code> 直接:</ p>

  _,err:= c.ResponseWriter.Write(json_msg)
</ code> </ pre>

那是 稍稍</ em>。 事实证明,有一种甚至更好的方法来做到这一点:使用 json.Encoder </ code>。 json.Encoder </ code>是一种将 embeds </ em>嵌入 io.Writer </ code>的结构,可以有效地添加到任何 io.Writer </ code>结构中 Encode </ code>方法,该方法会将结构编码为json并将其写入writer。 区别在于您正在执行的操作将数据编码为内存中的字节片,然后将其复制到 io.Writer </ code>中,此时您可以直接将其写入,如下所示:</ p >

  err:= json.NewEncoder(c.ResponseWriter).Encode(m)
</ code> </ pre>

,现在您不需要 甚至具有中间的 [] byte </ code>格式。</ p>
</ div>

展开原文

原文

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.



您正在使用 json_msg </ code>作为 Printf </ code>类型函数中的格式字符串, 仅将 string </ code>作为格式字符串( [] byte </ code>和 string </ code>是不同的类型,尽管可以将它们相互转换)。 写入字节片的正确方法是指定格式字符串:</ p>

  fmt.Fprintf(WRITER_OBJ,“%s”,json_msg)
</ code> < / pre>

这将打印 [] byte </ code>为Unicode内容。 在Fprintf / Printf中,不应将变量用作格式字符串。 我认为这不会像C中那样有问题。但是,如果您的JSON中包含“%”,则可能会引起问题。</ p>
</ div>

展开原文

原文

You are using json_msg as the format string in a Printf type function, which only excepts string as the format string ([]byte and string are distinct types. Although you can cast them to each other). The proper way of writing a byte slice would be to specify the format string:

fmt.Fprintf(WRITER_OBJ, "%s", json_msg)

This will print the []byte as it's Unicode contents. You shouldn't use varibles as the format string in Fprintf/Printf. I don't think it's a problematic as it would be in C. But it might cause issues if a "%" got in your JSON.



  fmt.Fprintf(c.ResponseWriter,string(json_msg))
</ code> </ pre>

[] byte </ code>强制转换为 string </ code> </ p>
</ div>的正确方法

展开原文

原文

fmt.Fprintf(c.ResponseWriter, string(json_msg))

Would be correct way to cast your []byte to a string

dongrouyuan5685
dongrouyuan5685 string(json_msg)是格式字​​符串。
7 年多之前 回复
drelgkxl93433
drelgkxl93433 该调用中缺少格式字符串。
7 年多之前 回复
douchen7555
douchen7555 是的,如果将字节转换为字符串。 但是他的问题表现出对如何正确地总体上表现出一些无知。 我试图解决这个问题。
7 年多之前 回复
dongshuo6503
dongshuo6503 通常认为不良的内存管理在不必要时进行转换。 强制转换会创建一个副本,在这种情况下,您还有其他不错的选择(Write()和FPrintf(“%v”))
7 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问