解码大流JSON

我有一个巨大的 JSON 数组存储在一个文件(“file.json”)中,我需要遍历该数组并对每个元素进行一些操作。

err = json.Unmarshal(dat, &all_data)

导致内存不足 - 我猜是因为它首先将所有内容加载到内存中。

有没有办法按元素流式传输 JSON 元素?


富国沪深
浏览 169回答 2
2回答

一只甜甜圈

因此,正如评论者所建议的,您可以使用“encoding/json”的流 API 一次读取一个字符串:r := ... // get some io.Reader (e.g. open the big array file)d := json.NewDecoder(r)// read "["d.Token()// read strings one by onefor d.More() {    s, _ := d.Token()    // do something with s which is the newly read string    fmt.Printf("read %q\n", s)}// (optionally) read "]"d.Token()请注意,为简单起见,我省略了需要实现的错误处理。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go