简体   繁体   English

如何在Go中json解码接口切片?

[英]How do I json decode interface slice in Go?

I am json.Decode()'ing (forgive the shorthand) a json response from an api into a large struct. 我是json.Decode()'(原谅速记)从api到大型结构的json响应。 Within that struct are a few types that are of type []interface{}. 在该结构中,有几种类型为[] interface {}的类型。 I can't figure out how to extract any data from those special nested structs. 我不知道如何从那些特殊的嵌套结构中提取任何数据。 I have tried using a case switch type checking solution but came up empty handed still. 我曾尝试使用案例切换类型检查解决方案,但仍然空手而归。 Can someone share their experience with a similar case or point me in the right direction? 有人可以分享他们在类似案件中的经验或为我指出正确的方向吗?

m := new(largestruct)
if err := json.NewDecoder(resp.Body).Decode(&m); err != nil{
return err
}

The struct field for interface is: 接口的struct字段是:

Strings []interface{} `json:"strings"`

Using the switch case you can fetch the value underlying the interface. 使用切换用例,您可以获取接口基础的值。 The function will run recursively until it gets the original type of the parsed json. 该函数将递归运行,直到获得解析的json的原始类型为止。

func fetchValue(value interface{}) { // pass the interface value from the struct in this function as it will run recursively to get the value.
    switch value.(type) {
    case string:
        fmt.Printf("%v is an string \n ", value.(string))
    case bool:
        fmt.Printf("%v is bool \n ", value.(bool))
    case float64:
        fmt.Printf("%v is float64 \n ", value.(float64))
    case []interface{}:
        fmt.Printf("%v is a slice of interface \n ", value)
        for _, v := range value.([]interface{}) {
            fetchValue(v)
        }
    case map[string]interface{}:
        fmt.Printf("%v is a map \n ", value)
        for _, v := range value.(map[string]interface{}) {
            fetchValue(v)
        }
    default:
        fmt.Printf("%v is unknown \n ", value)
    }
}

The reason behind the types in switch to be limited is defined in the golang spec for unmarshal where it is clearly described what values the json will parse into when unmarshaling using interface{}: gomar规范中对unmarshal定义了switch中的类型受到限制的原因,其中明确描述了在使用interface {}解组时json将解析为哪些值:

To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value: 要将JSON解组为接口值,Unmarshal将其中之一存储在接口值中:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM