0

我有一个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"}]}
4

1 回答 1

2

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

在操场上运行它

于 2020-01-14T05:53:21.140 回答