doutangshuan6473 2014-06-24 03:32
浏览 87
已采纳

解组后访问嵌套JSON数组的Golang问题

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

  • 写回答

2条回答 默认 最新

  • dongxi6897 2014-06-24 03:46
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上