使用嵌入数组分析JSON字节流时出现运行时错误
我能够将一个简单的JSON对象解析为一个结构,但是当我试图解析该对象内部的数组时,我得到的使用嵌入数组分析JSON字节流时出现运行时错误,json,go,Json,Go,我能够将一个简单的JSON对象解析为一个结构,但是当我试图解析该对象内部的数组时,我得到的索引超出了范围 package main import ( "fmt" "encoding/json" ) type jsonobject struct { Objects []ObjectType `json:"objects"` } type ObjectType struct { Name string `json:"name"` } func main() {
索引超出了范围
package main
import (
"fmt"
"encoding/json"
)
type jsonobject struct {
Objects []ObjectType `json:"objects"`
}
type ObjectType struct {
Name string `json:"name"`
}
func main() {
// Simple element
bytes := []byte(`{ "name": "foo" }`)
var objecttype ObjectType
json.Unmarshal(bytes, &objecttype)
fmt.Printf("Results: %v\n", objecttype.Name) // Results: localhost
// Object with embedded array
bytes = []byte(`{ "objects": [ "name": "foo" ] }`)
jsontype := &jsonobject{}
json.Unmarshal(bytes, &jsontype)
fmt.Printf("Results: %v\n", jsontype.Objects[0].Name) // panic: runtime error: index out of range
}
因为您的JSON输入不是您在Go中建模的内容。因此JSON数组不会被解包到jsonobject.Objects
:它将保持nil
;因此,尝试对其进行索引将导致索引超出范围
错误
尝试从以下内容中取消编组:
bytes = []byte(`{ "objects": [ {"name": "foo"} ] }`)
请注意,JSON数组中的元素(本例中为一个元素)也在大括号(JSON对象)中
试穿一下。谢谢!当我看到您在数组中的元素周围添加的括号时,我意识到了我的错误。