英文:
Golang issue with accessing Nested JSON Array after Unmarshalling
问题
我还在学习Go语言的过程中,但在处理JSON响应数组时遇到了问题。每当我尝试访问"objects"数组的嵌套元素时,Go会抛出错误(类型interface {}不支持索引)。
出了什么问题,我如何避免将来犯同样的错误?
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)
	}
	objects := result["objects"].([]interface{})
	firstObject := objects[0].(map[string]interface{})
	fmt.Println(firstObject["ITEM_ID"])
}
链接:http://play.golang.org/p/duW-meEABJ
编辑:修复了链接。
英文:
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
答案1
得分: 28
根据错误提示,接口变量不支持索引。你需要使用类型断言将其转换为底层类型。
在解码为interface{}变量时,JSON模块将数组表示为[]interface{}切片,将字典表示为map[string]interface{}映射。
如果没有错误检查,你可以使用以下代码深入到这个JSON中:
objects := result["objects"].([]interface{})
first := objects[0].(map[string]interface{})
fmt.Println(first["ITEM_ID"])
如果类型不匹配,这些类型断言将会引发恐慌。你可以使用两个返回值的形式来检查错误。例如:
objects, ok := result["objects"].([]interface{})
if !ok {
    // 在这里处理错误
}
如果JSON遵循已知的格式,更好的解决方案是解码为一个结构体。根据你的示例数据,以下代码可能适用:
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"`
}
如果你解码为这种类型,可以通过result.Objects[0].ItemId访问项目ID。
英文:
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.
答案2
得分: 0
对于那些可能正在寻找与我类似解决方案的人,https://github.com/Jeffail/gabs 提供了更好的解决方案。
我在这里提供一个示例。
package main
import (
	"encoding/json"
	"fmt"
	"github.com/Jeffail/gabs"
)
func main() {
	payload := []byte(`{
		"query": "QEACOR139GID",
		"count": 1,
		"objects": [{
			"ITEM_ID": "QEACOR139GID",
			"PROD_CLASS_ID": "BMXCPGRIPS",
			"AVAILABLE": 19,
			"Messages": [{
					"first": {
						"text": "sth, 1st"
					}
				},
				{
					"second": {
						"text": "sth, 2nd"
					}
				}
			]
		}]
	}`)
	fmt.Println("使用 gabs:")
	jsonParsed, _ := gabs.ParseJSON(payload)
	data := jsonParsed.Path("objects").Data()
	fmt.Println("  获取数据:")
	fmt.Println("    ", data)
	children, _ := jsonParsed.Path("objects").Children()
	fmt.Println("  从\"objects\"获取的子数组:")
	for key, child := range children {
		fmt.Println("    ", key, ":", child)
		children2, _ := child.Path("Messages").Children()
		fmt.Println("    从\"Messages\"获取的子数组:")
		for key2, child2 := range children2 {
			fmt.Println("      ", key2, ":", child2)
		}
	}
}
英文:
For who those might looking for similar solution like me,  https://github.com/Jeffail/gabs provides better solution.
I provide the example here.
package main
import (
	"encoding/json"
	"fmt"
	"github.com/Jeffail/gabs"
)
func main() {
	payload := []byte(`{
		"query": "QEACOR139GID",
		"count": 1,
		"objects": [{
			"ITEM_ID": "QEACOR139GID",
			"PROD_CLASS_ID": "BMXCPGRIPS",
			"AVAILABLE": 19, 
			"Messages": [ {
					"first": {
						"text":  "sth, 1st"
					}
				},
				{
						"second": {
						"text": "sth, 2nd"
					}
			  }
			]
		}]
	}`)
	fmt.Println("Use gabs:")
	jsonParsed, _ := gabs.ParseJSON(payload)
	data := jsonParsed.Path("objects").Data()
	fmt.Println("  Fetch Data: ")
	fmt.Println("    ", data)
	children, _ := jsonParsed.Path("objects").Children()
	fmt.Println("  Children Array from \"Objects\": ")
	for key, child := range children {
		fmt.Println("    ", key, ": ", child)
		children2, _ := child.Path("Messages").Children()
		fmt.Println("    Children Array from \"Messages\": ")
		for key2, child2 := range children2 {
			fmt.Println("      ", key2, ": ", child2)
		}
	}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论