gpt4 book ai didi

go - 将非常大的 json 解码为结构数组

转载 作者:IT王子 更新时间:2023-10-29 00:54:53 26 4
gpt4 key购买 nike

我有一个具有 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 作为流处理并从这个集合中逐一解码结构?

最佳答案

首先,阅读文档。


Package json

import "encoding/json"

func (*Decoder) Decode

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

Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v.

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

Playground: 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)

}

关于go - 将非常大的 json 解码为结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54316192/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com