流式传输和解析文件中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。解码器在流模式下读取顶级对象。详见评论。

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 %#vn", key, value)
}
return nil
}

这样使用:

err := decodeStream(f) // f is the *os.File
if err != nil {
// handle error
}

在围棋赛场上奔跑。

最新更新