栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何正确解组不同类型的数组?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何正确解组不同类型的数组?

Go官方博客上有一篇不错的文章

encoding/json
:JSON和GO。可以将“任意数据解码”到接口{}中,并使用类型断言来动态确定类型。

您的代码可能可以修改为:

package mainimport (    "encoding/json"    "fmt")var my_json string = `{    "an_array":[    "with_a string",    {        "and":"some_more",        "different":["nested", "types"]    }    ]}`func WTHisThisJSON(f interface{}) {    switch vf := f.(type) {    case map[string]interface{}:        fmt.Println("is a map:")        for k, v := range vf { switch vv := v.(type) { case string:     fmt.Printf("%v: is string - %qn", k, vv) case int:     fmt.Printf("%v: is int - %qn", k, vv) default:     fmt.Printf("%v: ", k)     WTHisThisJSON(v) }        }    case []interface{}:        fmt.Println("is an array:")        for k, v := range vf { switch vv := v.(type) { case string:     fmt.Printf("%v: is string - %qn", k, vv) case int:     fmt.Printf("%v: is int - %qn", k, vv) default:     fmt.Printf("%v: ", k)     WTHisThisJSON(v) }        }    }}func main() {    fmt.Println("JSON:n", my_json, "n")    var f interface{}    err := json.Unmarshal([]byte(my_json), &f)    if err != nil {        fmt.Println(err)    } else {        fmt.Printf("JSON: ")        WTHisThisJSON(f)    }}

它给出的输出如下:

JSON: {    "an_array":[    "with_a string",    {        "and":"some_more",        "different":["nested", "types"]    }    ]}JSON: is a map:an_array: is an array:0: is string - "with_a string"1: is a map:and: is string - "some_more"different: is an array:0: is string - "nested"1: is string - "types"

尚未完成,但显示了它如何工作。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/430604.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号