【问题标题】:Decode very big json to array of structs将非常大的 json 解码为结构数组
【发布时间】:2019-01-22 20:46:15
【问题描述】:

我有一个具有 REST API 的 Web 应用程序,获取 JSON 作为输入并执行此 JSON 的转换。

这是我的代码:

func (a *API) getAssignments(w http.ResponseWriter, r *http.Request) {

   var document DataPacket
   err := json.NewDecoder(r.Body).Decode(&document)
   if err != nil {
       a.handleJSONParseError(err, w)
      return
   }

   // transformations
我得到的

JSON 是结构的 collection。外部应用程序使用我的应用程序并向我发送非常大的 json 文件 (300-400MB)。一次解码这个 json 需要非常大的时间和大量的内存。

有没有办法将此 json 作为流处理并从该集合中一一解码结构?

【问题讨论】:

标签: go


【解决方案1】:

首先,阅读文档。


Package json

导入“编码/json”

func (*Decoder) Decode

func (dec *Decoder) Decode(v interface{}) error

Decode 从其输入中读取下一个 JSON 编码值并将其存储 在 v 所指向的值中。

Example (Stream): This example uses a Decoder to decode a streaming array of JSON objects.

游乐场:https://play.golang.org/p/o6hD-UV85SZ

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "strings"
)

func main() {
    const jsonStream = `
    [
        {"Name": "Ed", "Text": "Knock knock."},
        {"Name": "Sam", "Text": "Who's there?"},
        {"Name": "Ed", "Text": "Go fmt."},
        {"Name": "Sam", "Text": "Go fmt who?"},
        {"Name": "Ed", "Text": "Go fmt yourself!"}
    ]
`
    type Message struct {
        Name, Text string
    }
    dec := json.NewDecoder(strings.NewReader(jsonStream))

    // read open bracket
    t, err := dec.Token()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%T: %v\n", t, t)

    // while the array contains values
    for dec.More() {
        var m Message
        // decode an array value (Message)
        err := dec.Decode(&m)
        if err != nil {
            log.Fatal(err)
        }

        fmt.Printf("%v: %v\n", m.Name, m.Text)
    }

    // read closing bracket
    t, err = dec.Token()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%T: %v\n", t, t)

}

【讨论】:

    猜你喜欢
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多