访问Unmarshalling之后访问嵌套JSON数组的Golang问题 [英] Golang issue with accessing Nested JSON Array after Unmarshalling
问题描述
我仍然在Go的学习过程中,但是当涉及到JSON响应数组时,我碰到了一堵墙。每当我尝试访问objects数组的嵌套元素时,Go引发(类型接口{}不支持索引)
什么地方出问题了,我怎么能避免在将来出现这个错误?
package main
import(
encoding / json
fmt
)
func main(){
payload:= [] byte(`{query:QEACOR139GID, count:1,objects:[{ITEM_ID:QEACOR139GID,PROD_CLASS_ID:BMXCPGRIPS,AVAILABLE:19}]}`)
var result map [string] interface {}
if err:= json.Unmarshal(payload,& result); err!= nil {
panic(err)
}
fmt.Println(result [objects] [ITEM_ID])
}
http://play.golang.org/p/duW-meEABJ
编辑:固定链接
正如错误所述,接口变量不支持索引。您需要使用类型断言转换为基础类型。
解码到 interface {}
变量时,JSON模块将数组表示为 [] interface {}
切片和字典作为 map [string] interface {}
maps。
如果没有错误检查,您可以深入了解这个JSON类似于:
objects:= result [objects]。([] interface {})
first:= objects [0]。(map [string] interface {})
fmt.Println(first [ITEM_ID])
如果类型不匹配,这些类型断言会惊慌失措。你可以使用双返回表格,你可以检查这个错误。例如:
objects,ok:= result [objects]。([] interface {})
if!ok {
//处理错误
}
如果JSON尽管遵循已知的格式,但更好的解决方案是将其解码为结构。给出你的例子中的数据,下面的例子可能会做到:
$ $ p $ $ $ $ $ $ $ $ $ $ $ $ $结果结构{
查询字符串`json:查询`
计数int`json:count`
对象[]结构{
ItemId字符串`json:ITEM_ID`
ProdClassId string`json:PROD_CLASS_ID `
可用的int`json:AVAILABLE`
}`json:objects`
}
如果您解码为此类型,则可以以 result.Objects [0] .ItemId
的形式访问项目标识。
I'm still in the learning process of Go but am hitting a wall when it comes to JSON response arrays. Whenever I try to access a nested element of the "objects" array, Go throws (type interface {} does not support indexing)
What is going wrong and how can I avoid making this mistake in the future?
package main
import (
"encoding/json"
"fmt"
)
func main() {
payload := []byte(`{"query": "QEACOR139GID","count": 1,"objects": [{"ITEM_ID": "QEACOR139GID","PROD_CLASS_ID": "BMXCPGRIPS","AVAILABLE": 19}]}`)
var result map[string]interface{}
if err := json.Unmarshal(payload, &result); err != nil {
panic(err)
}
fmt.Println(result["objects"]["ITEM_ID"])
}
http://play.golang.org/p/duW-meEABJ
edit: Fixed link
As the error says, interface variables do not support indexing. You will need to use a type assertion to convert to the underlying type.
When decoding into an interface{}
variable, the JSON module represents arrays as []interface{}
slices and dictionaries as map[string]interface{}
maps.
Without error checking, you could dig down into this JSON with something like:
objects := result["objects"].([]interface{})
first := objects[0].(map[string]interface{})
fmt.Println(first["ITEM_ID"])
These type assertions will panic if the types do not match. You can use the two-return form, you can check for this error. For example:
objects, ok := result["objects"].([]interface{})
if !ok {
// Handle error here
}
If the JSON follows a known format though, a better solution would be to decode into a structure. Given the data in your example, the following might do:
type Result struct {
Query string `json:"query"`
Count int `json:"count"`
Objects []struct {
ItemId string `json:"ITEM_ID"`
ProdClassId string `json:"PROD_CLASS_ID"`
Available int `json:"AVAILABLE"`
} `json:"objects"`
}
If you decode into this type, you can access the item ID as result.Objects[0].ItemId
.
这篇关于访问Unmarshalling之后访问嵌套JSON数组的Golang问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!