Golang issue with accessing Nested JSON Array after Unmarshalling

后端 未结 2 1849
独厮守ぢ
独厮守ぢ 2020-12-28 18:09

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

2条回答
  •  既然无缘
    2020-12-28 18:40

    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.

提交回复
热议问题