首页 > 解决方案 > 从文件中流式传输并解析大量 json 对象集合(不是数组)

问题描述

我需要从大型 json 文件中流式传输并解析以下格式的 json?我尝试了仅解析数组的常用方法,但对于以下格式它失败了。

{
    "ABCD": {
        "name": "John",
        "cars": [],
        "nums": [],
        "id": "52000"
    },
    "WXYZ": {
        "name": "Jone",
        "cars": [],
        "nums": [],
        "id": "32000"
    },
    ...
}

标签: jsongo

解决方案


声明一个表示值的类型:

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
}

在 Go Playground 上运行它


推荐阅读