首頁  >  文章  >  後端開發  >  如何存取嵌套結構元素

如何存取嵌套結構元素

王林
王林轉載
2024-02-09 08:00:11819瀏覽

如何存取嵌套結構元素

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中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除