3 回答

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在本機上遍歷結構,操作未定義。

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)
}
}
}

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")
}
}
- 3 回答
- 0 關注
- 340 瀏覽
添加回答
舉報