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 都应该警告您这一点。
以上就是如何访问嵌套结构元素的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号