卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34651本站已运行393

如何访问嵌套结构元素

如何访问嵌套结构元素

php小编西瓜将为大家介绍如何访问嵌套结构元素。在编程中,嵌套结构常常用于表示复杂的数据结构,如多层数组或对象。要访问嵌套结构中的元素,我们需要使用适当的语法和方法。本文将详细解释如何按照层级逐步访问和获取嵌套结构中的元素,帮助读者更好地理解和处理嵌套结构数据。无论您是初学者还是有一定经验的开发者,本文都将为您提供实用的技巧和示例,帮助您轻松应对访问嵌套结构元素的需求。

问题内容

我有这样的结构。我想将我的 json 解析为这个结构。但我无法访问嵌套结构。

我希望能够达到类似的子结构,但我不能:

func main() {
    str := `[{
        "applicationdefaults":  {
            "applicationpoolname": "defaultapppool",
                ....
    }]`

    mdl := foo(str)

    // mdl.applicationdefaults ?? i can't reach like this. there are only a few functions like: append!, last! , print!, range!, reverse!, sort!, var!
}

有人帮忙吗?

我的结构:

package model

type sitesdetails []struct {
    applicationdefaults struct {
        applicationpoolname string      `json:"applicationpoolname"`
        enabledprotocols    string      `json:"enabledprotocols"`
        attributes          string      `json:"attributes"`
        childelements       string      `json:"childelements"`
        elementtagname      string      `json:"elementtagname"`
        islocallystored     bool        `json:"islocallystored"`
        methods             interface{} `json:"methods"`
        rawattributes       string      `json:"rawattributes"`
        schema              string      `json:"schema"`
    } `json:"applicationdefaults"`
    applications []string `json:"applications"`
    bindings     []string `json:"bindings"`
    id           int      `json:"id"`
    limits       struct {
        connectiontimeout string      `json:"connectiontimeout"`
        maxbandwidth      int64       `json:"maxbandwidth"`
        maxconnections    int64       `json:"maxconnections"`
        maxurlsegments    int         `json:"maxurlsegments"`
        attributes        string      `json:"attributes"`
        childelements     string      `json:"childelements"`
        elementtagname    string      `json:"elementtagname"`
        islocallystored   bool        `json:"islocallystored"`
        methods           interface{} `json:"methods"`
        rawattributes     string      `json:"rawattributes"`
        schema            string      `json:"schema"`
    } `json:"limits"`
}

这是我用于将 json 解析为结构的代码:

func foo(resp string) model.SitesDetails {
    data := []byte(resp)

    var m model.SitesDetails
    err := json.Unmarshal(data, &m)
    if err != nil {
        log.Fatal(err)
    }
    return m
}

解决方法

您在这里解组到一个切片(因为您的 sitesdetails 类型是 []struct 并且您的 json 以数组开头),所以您应该能够通过访问您的详细信息

poolName := model[0].ApplicationDefaults.ApplicationPoolName

这也解释了为什么您的 ide 只建议可应用于切片的操作,例如附加(我猜这会插入正确的代码以附加到您的切片)。

顺便说一句,你真的不应该调用你的变量 model ,因为这也是你显然用于你的包的名称(你正在使用 model.sitesdetails ),所以你的变量名称会在此时隐藏该包- 这可能会导致极大的混乱,任何像样的 ide 都应该警告您这一点。

卓越飞翔博客
上一篇: 为什么下面的 go 程序会出现死锁错误“致命错误:所有 goroutine 都在睡眠 - 死锁!”
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏