亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Go 中使用嵌套的 []struct 循環?

在 Go 中使用嵌套的 []struct 循環?

Go
慕的地8271018 2021-11-08 15:48:31
我有一個正在使用的結構,但我不確定如何正確遍歷它。我想訪問字段名稱,但它所做的只是在每個循環中遞增計數。這是我的結構:type ImgurJson struct {      Status int16 `json:"status"`      Success bool `json:"success"`      Data []struct {            Width int16 `json:"width"`            Points int32 `json:"points"`            CommentCount int32 `json:"comment_count"`            TopicId int32 `json:"topic_id"`            AccountId int32 `json:"account_id"`            Ups int32 `json:"ups"`            Downs int32 `json:"downs"`            Bandwidth int64 `json:"bandwidth"`            Datetime int64 `json:"datetime"`            Score int64 `json:"score"`            Account_Url string `json:"account_url"`            Topic string `json:"topic"`            Link string `json:"link"`            Id string `json:"id"`            Description string`json:"description"`            CommentPreview string `json:"comment_preview"`            Vote string `json:"vote"`            Title string `json:"title"`            Section string `json:"section"`            Favorite bool `json:"favorite"`            Is_Album bool `json:"is_album"`            Nsfw bool `json:"nsfw"`             } `json:"data"`}這是我的功能:func parseJson(file string) {      jsonFile, err := ioutil.ReadFile(file)      if err != nil {            ...            }      jsonParser := ImgurJson{}      err = json.Unmarshal(jsonFile, &jsonParser)      for field, value := range jsonParser.Data {            fmt.Print("key: ", field, "\n")            fmt.Print("value: ", value, "\n")      }}如何循環遍歷 Go 中的嵌套 []struct 并返回字段?我看過幾篇關于反思的帖子,但我不明白這是否對我有幫助。我可以返回每個字段的值,但我不明白如何將字段名稱映射到鍵值。將“keys”重命名為“field”,抱歉!沒有意識到它們被稱為字段。我希望能夠打印:field: Width value: 1234我想了解如何執行此操作,以便稍后可以按名稱調用特定字段,以便將其映射到 SQL 列名稱。
查看完整描述

3 回答

?
HUX布斯

TA貢獻1876條經驗 獲得超6個贊

這段基于示例的代碼應該為您完成;http://blog.golang.org/laws-of-reflection


import "reflect"



for _, value := range jsonParser.Data {

            s := reflect.ValueOf(&value).Elem()

            typeOfT := s.Type()

            for i := 0; i < s.NumField(); i++ {

            f := s.Field(i)

            fmt.Print("key: ", typeOfT.Field(i).Name, "\n")

            fmt.Print("value: ", f.Interface(), "\n")

       }


}

請注意,在您的原始代碼中,循環正在迭代名為Data. 這些東西中的每一個都是該匿名結構類型的對象。那時您還沒有處理字段,從那里,您可以利用該reflect包打印結構中字段的名稱和值。您不能僅range在本機上遍歷結構,操作未定義。


查看完整回答
反對 回復 2021-11-08
?
哆啦的時光機

TA貢獻1779條經驗 獲得超6個贊

這是我們在評論中討論的另一種方法:


請記住,雖然這比反射更快,但直接使用結構字段并將其設為指針 ( Data []*struct{....})仍然更好、更有效。


type ImgurJson struct {

    Status  int16                    `json:"status"`

    Success bool                     `json:"success"`

    Data    []map[string]interface{} `json:"data"`

}

//.....

for i, d := range ij.Data {

    fmt.Println(i, ":")

    for k, v := range d {

        fmt.Printf("\t%s: ", k)

        switch v := v.(type) {

        case float64:

            fmt.Printf("%v (number)\n", v)

        case string:

            fmt.Printf("%v (str)\n", v)

        case bool:

            fmt.Printf("%v (bool)\n", v)

        default:

            fmt.Printf("%v (%T)\n", v, v)

        }

    }

}


查看完整回答
反對 回復 2021-11-08
?
翻過高山走不出你

TA貢獻1875條經驗 獲得超3個贊

您還可以在嵌套結構上使用普通的 golang for 循環進行迭代。


type ImgurJson struct {

      Status int16 `json:"status"`

      Success bool `json:"success"`

      Data []struct {

            Width int16 `json:"width"`

            Points int32 `json:"points"`

            CommentCount int32 `json:"comment_count"`

            TopicId int32 `json:"topic_id"`

            AccountId int32 `json:"account_id"`

            Ups int32 `json:"ups"`

            Downs int32 `json:"downs"`

            Bandwidth int64 `json:"bandwidth"`

            Datetime int64 `json:"datetime"`

            Score int64 `json:"score"`

            Account_Url string `json:"account_url"`

            Topic string `json:"topic"`

            Link string `json:"link"`

            Id string `json:"id"`

            Description string`json:"description"`

            CommentPreview string `json:"comment_preview"`

            Vote string `json:"vote"`

            Title string `json:"title"`

            Section string `json:"section"`

            Favorite bool `json:"favorite"`

            Is_Album bool `json:"is_album"`

            Nsfw bool `json:"nsfw"`

             } `json:"data"`

}


func parseJson(file string) {

      jsonFile, err := ioutil.ReadFile(file)

      if err != nil {

            ...

            }

      jsonParser := ImgurJson{}

      err = json.Unmarshal(jsonFile, &jsonParser)

      for i :=0; i<len(jsonParser.Data); i++ {

            fmt.Print("key: ", jsonParser.Data[i].TopicId, "\n")

      }

}


查看完整回答
反對 回復 2021-11-08
  • 3 回答
  • 0 關注
  • 340 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號