猿问

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

我有一个正在使用的结构,但我不确定如何正确遍历它。我想访问字段名称,但它所做的只是在每个循环中递增计数。


这是我的结构:


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 列名称。


慕的地8271018
浏览 306回答 3
3回答

HUX布斯

这段基于示例的代码应该为您完成;http://blog.golang.org/laws-of-reflectionimport "reflect"for _, value := range jsonParser.Data {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; s := reflect.ValueOf(&value).Elem()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; typeOfT := s.Type()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < s.NumField(); i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f := s.Field(i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Print("key: ", typeOfT.Field(i).Name, "\n")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Print("value: ", f.Interface(), "\n")&nbsp; &nbsp; &nbsp; &nbsp;}}请注意,在您的原始代码中,循环正在迭代名为Data. 这些东西中的每一个都是该匿名结构类型的对象。那时您还没有处理字段,从那里,您可以利用该reflect包打印结构中字段的名称和值。您不能仅range在本机上遍历结构,操作未定义。

哆啦的时光机

这是我们在评论中讨论的另一种方法:请记住,虽然这比反射更快,但直接使用结构字段并将其设为指针 ( Data []*struct{....})仍然更好、更有效。type ImgurJson struct {&nbsp; &nbsp; Status&nbsp; int16&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; `json:"status"`&nbsp; &nbsp; Success bool&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;`json:"success"`&nbsp; &nbsp; Data&nbsp; &nbsp; []map[string]interface{} `json:"data"`}//.....for i, d := range ij.Data {&nbsp; &nbsp; fmt.Println(i, ":")&nbsp; &nbsp; for k, v := range d {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("\t%s: ", k)&nbsp; &nbsp; &nbsp; &nbsp; switch v := v.(type) {&nbsp; &nbsp; &nbsp; &nbsp; case float64:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%v (number)\n", v)&nbsp; &nbsp; &nbsp; &nbsp; case string:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%v (str)\n", v)&nbsp; &nbsp; &nbsp; &nbsp; case bool:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%v (bool)\n", v)&nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%v (%T)\n", v, v)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

翻过高山走不出你

您还可以在嵌套结构上使用普通的 golang for 循环进行迭代。type ImgurJson struct {&nbsp; &nbsp; &nbsp; Status int16 `json:"status"`&nbsp; &nbsp; &nbsp; Success bool `json:"success"`&nbsp; &nbsp; &nbsp; Data []struct {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Width int16 `json:"width"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Points int32 `json:"points"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CommentCount int32 `json:"comment_count"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; TopicId int32 `json:"topic_id"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; AccountId int32 `json:"account_id"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Ups int32 `json:"ups"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Downs int32 `json:"downs"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Bandwidth int64 `json:"bandwidth"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Datetime int64 `json:"datetime"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Score int64 `json:"score"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Account_Url string `json:"account_url"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Topic string `json:"topic"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Link string `json:"link"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Id string `json:"id"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Description string`json:"description"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CommentPreview string `json:"comment_preview"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Vote string `json:"vote"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Title string `json:"title"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Section string `json:"section"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Favorite bool `json:"favorite"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Is_Album bool `json:"is_album"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Nsfw bool `json:"nsfw"`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} `json:"data"`}func parseJson(file string) {&nbsp; &nbsp; &nbsp; jsonFile, err := ioutil.ReadFile(file)&nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; jsonParser := ImgurJson{}&nbsp; &nbsp; &nbsp; err = json.Unmarshal(jsonFile, &jsonParser)&nbsp; &nbsp; &nbsp; for i :=0; i<len(jsonParser.Data); i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Print("key: ", jsonParser.Data[i].TopicId, "\n")&nbsp; &nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Go
我要回答