将很大的json解码为结构数组

其余的部分 :

我有一个具有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是结构集合外部应用程序使用我的应用程序,并向我发送非常大的json文件(300-400MB)。一次解码此json需要大量时间和大量内存。

有什么方法可以将此json作为流工作,并可以逐个解码此集合中的结构?

peterSO:

首先,阅读文档。


包json

导入“ encoding / json”

func(* Decoder)解码

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

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

示例(流):此示例使用解码器解码JSON对象的流数组。

游乐场: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)

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章