如何使用 Golang 解析 ndjson 文件?

ASH*_*EEV 4 go ndjson

我有一个ndjson(换行符分隔的 JSON)文件,我需要解析它并获取某些逻辑操作的数据。有没有什么好的方法可以ndjson使用golang解析文件?下面给出了 ndjson 示例

{"a":"1","b":"2","c":[{"d":"100","e":"10"}]}
{"a":"2","b":"2","c":[{"d":"101","e":"11"}]}
{"a":"3","b":"2","c":[{"d":"102","e":"12"}]}
Run Code Online (Sandbox Code Playgroud)

Cer*_*món 6

encoding/json解码器根据值类型解析具有可选或必需空格的连续 JSON 文档。因为换行符是空格,所以解码器处理ndjson.

d := json.NewDecoder(strings.NewReader(stream))
for {
    // Decode one JSON document.
    var v interface{}
    err := d.Decode(&v)

    if err != nil {
        // io.EOF is expected at end of stream.
        if err != io.EOF {
            log.Fatal(err)
        }
        break
    }

    // Do something with the value.
    fmt.Println(v)
}
Run Code Online (Sandbox Code Playgroud)

在操场上运行它