json.Encoder似乎与json.Marshal。具体来说,它将在编码值的末尾添加新行。知道为什么吗?对我来说,这似乎是个虫子。
package main
import "fmt"
import "encoding/json"
import "bytes"
func main() {
    var v string
    v = "hello"
    buf := bytes.NewBuffer(nil)
    json.NewEncoder(buf).Encode(v)
    b, _ := json.Marshal(&v)
    fmt.Printf("%q, %q", buf.Bytes(), b)
}
这个输出
"\"hello\"\n", "\"hello\""
因为他们在使用时显式添加了换行符Encoder.Encode。这是该函数的源代码,它实际上声明在文档中添加了换行符(请参见文档的注释):
https://golang.org/src/encoding/json/stream.go?s=4272:4319#L173
// Encode writes the JSON encoding of v to the stream,
// followed by a newline character.
//
// See the documentation for Marshal for details about the
// conversion of Go values to JSON.
func (enc *Encoder) Encode(v interface{}) error {
    if enc.err != nil {
        return enc.err
    }
    e := newEncodeState()
    err := e.marshal(v)
    if err != nil {
        return err
    }
    // Terminate each value with a newline.
    // This makes the output look a little nicer
    // when debugging, and some kind of space
    // is required if the encoded value was a number,
    // so that the reader knows there aren't more
    // digits coming.
    e.WriteByte('\n')
    if _, err = enc.w.Write(e.Bytes()); err != nil {
        enc.err = err
    }
    encodeStatePool.Put(e)
    return err
}
现在,为什么Go开发人员除了“使输出看起来更好”之外还这样做?一个答案:
go json Encoder已针对流进行了优化(例如json数据的MB / GB / PB)。通常,在流式传输时,需要一种方法来确定流式传输何时完成。在的情况下Encoder.Encode(),这是\n换行符。当然,您当然可以写入缓冲区。但是您也可以写一个io.Writer,它将流式传输v。
与之相反的是json.Marshal,如果您的输入来自不受信任(且不受限制的未知)源(例如,Web服务的Ajax POST方法-如果有人发布100MB json文件怎么办?),通常不建议使用该方法。并且,json.Marshal这将是json的最终完整集-例如,您不会期望将几百个Marshal条目连接在一起。您将为此使用Encoder.Encode()来构建大型集合并写入缓冲区,流,文件,io.Writer等。
每当怀疑它是否是错误时,我都会一直在查找源代码-这是Go的优点之一,它是源代码,而编译器只是纯Go语言。在[N] VIM我使用\gb同一个浏览器中打开源定义我的.vimrc设置。
| 归档时间: | 
 | 
| 查看次数: | 2540 次 | 
| 最近记录: |