使用json.Decoder 可以解码 JSON 流。
使用Decoder.Decode(),我们可以读取(解组)单个值,而无需消耗和解组整个流。这很酷,但您的输入是“单个”JSON 对象,而不是一系列 JSON 对象,这意味着对 Decoder.Decode() 的调用将尝试解组包含所有项目(大对象)的完整 JSON 对象。
我们想要的是对单个 JSON 对象的部分即时处理。为此,我们可以使用Decoder.Token(),它仅解析(提前)JSON 输入流中的下一个后续标记并返回它。这称为事件驱动解析。
当然,我们必须“处理”(解释并采取行动)令牌并构建一个“状态机”来跟踪我们在处理的 JSON 结构中所处的位置。
这是一个解决您的问题的实现。
我们将使用以下 JSON 输入:
{
"somefield": "value",
"otherfield": "othervalue",
"items": [
{ "id": "1", "data": "data1" },
{ "id": "2", "data": "data2" },
{ "id": "3", "data": "data3" },
{ "id": "4", "data": "data4" }
]
}
并阅读items,由这种类型建模的“大对象”:
type LargeObject struct {
Id string `json:"id"`
Data string `json:"data"`
}
我们还将解析和解释 JSON 对象中的其他字段,但我们只会记录/打印它们。
为了简洁和简单的错误处理,我们将使用这个辅助错误处理函数:
he := func(err error) {
if err != nil {
log.Fatal(err)
}
}
现在让我们看看一些行动。在下面的示例中,为了简洁起见并在 Go Playground 上进行工作演示,我们将从 string 值中读取。要从实际的 HTTP 响应正文中读取,我们只需更改一行,这就是我们创建 json.Decoder 的方式:
dec := json.NewDecoder(res.Body)
所以演示:
dec := json.NewDecoder(strings.NewReader(jsonStream))
// We expect an object
t, err := dec.Token()
he(err)
if delim, ok := t.(json.Delim); !ok || delim != '{' {
log.Fatal("Expected object")
}
// Read props
for dec.More() {
t, err = dec.Token()
he(err)
prop := t.(string)
if t != "items" {
var v interface{}
he(dec.Decode(&v))
log.Printf("Property '%s' = %v", prop, v)
continue
}
// It's the "items". We expect it to be an array
t, err := dec.Token()
he(err)
if delim, ok := t.(json.Delim); !ok || delim != '[' {
log.Fatal("Expected array")
}
// Read items (large objects)
for dec.More() {
// Read next item (large object)
lo := LargeObject{}
he(dec.Decode(&lo))
fmt.Printf("Item: %+v\n", lo)
}
// Array closing delim
t, err = dec.Token()
he(err)
if delim, ok := t.(json.Delim); !ok || delim != ']' {
log.Fatal("Expected array closing")
}
}
// Object closing delim
t, err = dec.Token()
he(err)
if delim, ok := t.(json.Delim); !ok || delim != '}' {
log.Fatal("Expected object closing")
}
这将产生以下输出:
2009/11/10 23:00:00 Property 'somefield' = value
2009/11/10 23:00:00 Property 'otherfield' = othervalue
Item: {Id:1 Data:data1}
Item: {Id:2 Data:data2}
Item: {Id:3 Data:data3}
Item: {Id:4 Data:data4}
在Go Playground 上尝试完整的工作示例。