繁体   English   中英

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

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

我是json.Decode()'(原谅速记)从api到大型结构的json响应。 在该结构中,有几种类型为[] interface {}的类型。 我不知道如何从那些特殊的嵌套结构中提取任何数据。 我曾尝试使用案例切换类型检查解决方案,但仍然空手而归。 有人可以分享他们在类似案件中的经验或为我指出正确的方向吗?

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

接口的struct字段是:

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

使用切换用例,您可以获取接口基础的值。 该函数将递归运行,直到获得解析的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)
    }
}

gomar规范中对unmarshal定义了switch中的类型受到限制的原因,其中明确描述了在使用interface {}解组时json将解析为哪些值:

要将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