Why does json.Encoder add an extra line?

json.Encoderseems a little different from json.Marshal. In particular, it adds a new line to the end of the encoded value. Any idea why? This seems like a mistake.

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)
}

Displays

"\"hello\"\n", "\"hello\""

Try it in the Playground

+4
source share
2 answers

Because they explicitly added a new line symbol when used Encoder.Encode. Here's the source code for this func, and it actually claims to add a newline to the documentation (see Comment, which is the documentation):

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
}

Now, why did the Go developers do it differently than "making the conclusion a little enjoyable"? One answer:

Streaming

Go json Encoder (, MB/GB/PB json data). , , . Encoder.Encode(), \n newline. , . io.Writer, v.

json.Marshal, , , , ( ) (, ajax POST- -) - , - 100- json ?). json.Marshal json - . 100 Marshal . Encoder.Encode() , , , io.Writer ..

, , , - Go, - Go. [n] vim \gb, .vimrc.

+4

Encoder . - .

0

All Articles