【问题标题】:Decode JSON as it is still streaming in via net/http解码 JSON,因为它仍在通过 net/http 流式传输
【发布时间】:2017-11-02 14:00:25
【问题描述】:

过去我使用 go 从 API 端点解码 JSON,如下所示。

client := &http.Client{}

req, err := http.NewRequest("GET", "https://some/api/endpoint", nil)
res, err := client.Do(req)
defer res.Body.Close()

buf, _ := ioutil.ReadAll(res.Body)

// ... Do some error checking etc ...

err = json.Unmarshal(buf, &response)

我很快将致力于一个端点,它可以向我发送几兆字节的 JSON 数据,格式如下。

{
    "somefield": "value",
    "items": [
        { LARGE OBJECT },
        { LARGE OBJECT },
        { LARGE OBJECT },
        { LARGE OBJECT },
        ...
    ]
}

JSON 有时会包含一个大的、任意长度的对象数组。我想获取这些对象中的每一个并将它们分别放入消息队列中。我不需要自己解码对象。

如果我使用常规方法,这会在解码之前将整个响应加载到内存中。

当响应仍在流入并将其分派到队列中时,有没有一种好方法可以拆分每个 LARGE OBJECT 项?我这样做是为了避免在内存中保存尽可能多的数据。

【问题讨论】:

标签: json http go streaming


【解决方案1】:

使用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 上尝试完整的工作示例。

【讨论】:

【解决方案2】:

如果您想尽可能提高工作效率,您可以从流中读取键值对并使用mailru/easyjson 库中的词法分析器自行对其进行标记:

r := bufio.NewReader(stream)
for err == nil {
    pair, _ := r.ReadBytes(',')
    x := jlexer.Lexer{
        Data: pair,
    }
    fmt.Printf("%q = ", x.String())
    x.WantColon()
    fmt.Printf("%d\n", x.Int())
}

请注意,为简单起见,跳过了错误处理和一些额外的检查。这是完整的工作示例:https://play.golang.org/p/kk-7aEotqFd

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 2010-10-12
    • 2017-10-27
    • 2017-05-07
    相关资源
    最近更新 更多