嵌套结构元素的访问方法
时间:2024-02-10
浏览:432
作者:佚名
今天golang学习网给大家带来了《嵌套结构元素的访问方法》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~
问题内容
我有这样的结构。我想将我的 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 都应该警告您这一点。
好了,本文到此结束,带大家了解了《嵌套结构元素的访问方法》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.29
11.29
11.29
11.29
11.29
热门专题
