douri4459 2018-08-06 15:35
浏览 66

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

I am json.Decode()'ing (forgive the shorthand) a json response from an api into a large struct. Within that struct are a few types that are of type []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:

Strings []interface{} `json:"strings"`
  • 写回答

1条回答 默认 最新

  • dongshang3309 2018-08-06 15:56
    关注

    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.

    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 
     ", value.(string))
        case bool:
            fmt.Printf("%v is bool 
     ", value.(bool))
        case float64:
            fmt.Printf("%v is float64 
     ", value.(float64))
        case []interface{}:
            fmt.Printf("%v is a slice of interface 
     ", value)
            for _, v := range value.([]interface{}) {
                fetchValue(v)
            }
        case map[string]interface{}:
            fmt.Printf("%v is a map 
     ", value)
            for _, v := range value.(map[string]interface{}) {
                fetchValue(v)
            }
        default:
            fmt.Printf("%v is unknown 
     ", 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{}:

    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
    
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行