MarshalJSON 无需同时将所有对象放入内存中

Ili*_*oly 5 marshalling go

我想用来json.Encoder对大量数据流进行编码,而无需一次性将其全部加载到内存中。

// I want to marshal this
t := struct {
    Foo string

    // Bar is a stream of objects 
    // I don't want it all to be in memory at the same time.
    Bar chan string 
}{
    Foo: "Hello World",
    Bar: make(chan string),
}

// long stream of data
go func() {
    for _, x := range []string{"one", "two", "three"} {
        t.Bar <- x
    }
    close(t.Bar)
}()
Run Code Online (Sandbox Code Playgroud)

我想也许 json 包内置了这个功能,但事实并非如此。

操场

// error: json: unsupported type: chan string
if err := json.NewEncoder(os.Stdout).Encode(&t); err != nil {
    log.Fatal(err)
}
Run Code Online (Sandbox Code Playgroud)

我目前只是自己构建 json 字符串。

操场

w := os.Stdout
w.WriteString(`{ "Foo": "` + t.Foo + `", "Bar": [`)

for x := range t.Bar {
    _ = json.NewEncoder(w).Encode(x)
    w.WriteString(`,`)
}

w.WriteString(`]}`)
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?

如果json.Marshaler是这样的,那将是微不足道的。

type Marshaler interface {
    MarshalJSON(io.Writer) error
}
Run Code Online (Sandbox Code Playgroud)

Luk*_*uke 2

不幸的是,该encoding/json软件包还没有办法做到这一点。您现在所做的(手动)是最好的方法,无需修改内置包。

如果要打补丁encoding/json,可以修改encoding/json/encode.goreflectValueQuoted中的函数

您需要关注数组情况(切片有一个fallthrough):

// Inside switch:
case reflect.Array:
    e.WriteByte('[')
    n := v.Len()
    for i := 0; i < n; i++ {
        if i > 0 {
            e.WriteByte(',')
        }
        e.reflectValue(v.Index(i))
    }
    e.WriteByte(']')
Run Code Online (Sandbox Code Playgroud)

我假设您希望以同样的方式对待频道。它看起来像这样:

// Inside switch:
case reflect.Chan:
    e.WriteByte('[')
    i := 0
    for {
        x, ok := v.Recv()
        if !ok {
            break
        }
        if i > 0 {
            e.WriteByte(',')
        }
        e.reflectValue(x)
        i++
    }
    e.WriteByte(']')
Run Code Online (Sandbox Code Playgroud)

我没有对 中的通道做太多工作reflect,因此上述内容可能需要其他检查。

如果您最终选择了这条路线,您可以随时提交补丁。