gpt4 book ai didi

json - 如何处理 JSON 中的索引超出范围(Go)

转载 作者:数据小太阳 更新时间:2023-10-29 03:30:04 25 4
gpt4 key购买 nike

我正在开发一个 Web 服务,其中一部分我阅读了 Request.Body 并尝试对其进行解码。

if err := json.NewDecoder(body).Decode(r); err !=nil{
log.Error(err)
return err
}

问题是有时客户端发送一个空主体,我得到一个 panic 运行时错误:索引超出范围
协程 7 [正在运行]:
我应该如何缓解这种情况?

最佳答案

我正在分解你的代码:

NewDecoder :-

func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a new decoder that reads from r. The decoder introduces its own buffering and may read data from r beyond the JSON values requested.

所以NewDecoder只从r中读取数据。没关系,r 是空的吗...

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.

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

为了将 JSON 解码为接口(interface)值,Unmarshal 将其中一个存储在接口(interface)值中:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

If a JSON value is not appropriate for a given target type, or if a JSON number overflows the target type, Unmarshal skips that field and completes the unmarshalling as best it can. If no more serious errors are encountered, Unmarshal returns an UnmarshalTypeError describing the earliest such error.

The JSON null value unmarshals into an interface, map, pointer, or slice by setting that Go value to nil. Because null is often used in JSON to mean “not present,” unmarshaling a JSON null into any other Go type has no effect on the value and produces no error.

阅读上面的语句,很明显没有机会,我们得到运行时 panic 错误。我正在试验 sample code重现此错误。可能来自 JSON 包内部或您自己的代码的错误。

关于json - 如何处理 JSON 中的索引超出范围(Go),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27414264/

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