json - 从文件中流式传输并解析大量 json 对象集合(不是数组)
问题描述
我需要从大型 json 文件中流式传输并解析以下格式的 json?我尝试了仅解析数组的常用方法,但对于以下格式它失败了。
{
"ABCD": {
"name": "John",
"cars": [],
"nums": [],
"id": "52000"
},
"WXYZ": {
"name": "Jone",
"cars": [],
"nums": [],
"id": "32000"
},
...
}
解决方案
声明一个表示值的类型:
type Value struct {
Name string
Cars []string
Nums []int
ID string
}
使用流模式模式下的 json.Decoder 读取顶层对象。详情见评论。
func decodeStream(r io.Reader) error {
dec := json.NewDecoder(r)
// Expect start of object as the first token.
t, err := dec.Token()
if err != nil {
return err
}
if t != json.Delim('{') {
return fmt.Errorf("expected {, got %v", t)
}
// While there are more tokens in the JSON stream...
for dec.More() {
// Read the key.
t, err := dec.Token()
if err != nil {
return err
}
key := t.(string) // type assert token to string.
// Decode the value.
var value Value
if err := dec.Decode(&value); err != nil {
return err
}
// Add your code to process the key and value here.
fmt.Printf("key %q, value %#v\n", key, value)
}
return nil
}
像这样使用它:
err := decodeStream(f) // f is the *os.File
if err != nil {
// handle error
}
推荐阅读
- tcl - Tcl/Tk : 使用 tk 按钮执行 tcl 脚本
- codeigniter - 如何修复在codeigniter中在mpdf 5.7版本上加载pdf文档的错误?
- javascript - Checkbox not toggling in React with Material-UI
- python - AttributeError:“str”对象在构建逻辑回归模型时没有属性“decode”
- php - 如何在 Laravel 中将策略功能与中间件一起使用?
- utf-8 - raku:支持 Raku 2020.10 中的 utf8-c8 问题
- javascript - 如何检查按钮是否被按下javaScript
- javascript - 如何在javascript中使用正则表达式替换字符串?
- python - 从python中的不同文件夹导入文件
- iterm2 - iterm2中暗模式和亮模式切换的快捷键?