go - 我如何在 Go 中对接口(interface) slice 进行 json 解码?

标签 go

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

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

接口(interface)的结构字段是:

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

最佳答案

使用 switch case 你可以获取接口(interface)下的值。该函数将递归运行,直到它获取到解析后的 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)
    }
}

开关类型受限的原因在 golang spec for unmarshal 中定义。其中清楚地描述了在使用 interface{} 解码时 json 将解析成什么值:

To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

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

关于go - 我如何在 Go 中对接口(interface) slice 进行 json 解码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51711154/

相关文章:

go - golang/mongodb 聚合查询中复合文字中缺少类型

go - 无法为 gin web 框架 golang 编写单元测试

go - 如何获取父嵌入式结构字段值?

mongodb - 使用mongoDB汇总不同 “columns”中特定字段的列表

go - 为什么 net/rpc/client 的 Go 方法需要缓冲 channel ?

php - 从 PHP 的 shell_exec() 函数执行 Golang 二进制文件

arrays - 如何将未知大小的字节 slice 转换为字节数组?

git - 使用 libgit2/git2go 获取补丁的完整索引

go - 惯用的 goroutine 终止和错误处理

正则表达式在表达式中查找组