This question already has answers here:
Parsing multiple JSON objects in Go
(4个答案)
9个月前关闭。
我有一个
Run it on the playground。
(4个答案)
9个月前关闭。
我有一个
ndjson
(换行分隔的JSON)文件,我需要对其进行解析并获取用于某些逻辑操作的数据。有什么好的方法可以使用golang解析ndjson
文件。下面给出了一个示例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"}]}
最佳答案
encoding / json Decoder根据值类型解析具有可选或必需空格的顺序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 it on the playground。
07-26 04:17