英文:
Get keys and values from json.Decoder
问题
在你的代码中,你定义了一个名为Weather
的结构体,但是结构体字段的访问权限是私有的(小写字母开头),所以无法从JSON中解析出对应的值。你需要将字段的访问权限改为公有(大写字母开头),才能正确解析JSON。
此外,如果你需要处理具有未知字段的JSON,可以使用map[string]interface{}
类型来直接解析JSON并构建一个键值对的映射。这样可以灵活地处理任意字段的JSON数据。
以下是修改后的代码示例:
type Weather struct {
Name string `json:"name"`
}
// some code
decoder := json.NewDecoder(res.Body)
for {
var weather Weather
if err := decoder.Decode(&weather); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
fmt.Println(weather.Name)
}
希望对你有帮助!
英文:
Playing with Golang in my spare time. Trying to perform typical web task: get json from GET request and print its values.
type Weather struct {
name string
}
// some code
decoder := json.NewDecoder(res.Body)
for {
var weather Weather
if err := decoder.Decode(&weather); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
fmt.Println(weather.name)
}
JSON:
{"coord":{"lon":145.77,"lat":-16.92},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"base":"stations","main":{"temp":300.15,"pressure":1007,"humidity":74,"temp_min":300.15,"temp_max":300.15},"visibility":10000,"wind":{"speed":2.6,"deg":260},"clouds":{"all":20},"dt":1455633000,"sys":{"type":1,"id":8166,"message":0.0314,"country":"AU","sunrise":1455567124,"sunset":1455612583},"id":2172797,"name":"Cairns","cod":200}
As I understand, I need to declare a struct to get json values, but it prints nothing. What is my mistake?
And what if I need to operate json with unknown fields? Is there a way to construct map directly from json?
答案1
得分: 1
你的Weather
结构体中的name
字段是不可导出的。字段类型必须是可导出的,以便其他包可以看到它们(因此可以解组/解码为它们):https://tour.golang.org/basics/3
你还可以使用结构体标签将Go字段名映射到JSON键:
type Weather struct {
Name string `json:"name"`
}
...而且将来,你可以使用https://mholt.github.io/json-to-go/从JSON自动生成Go结构体。
英文:
Your 'name' field within your Weather
struct is unexported. Field types must be exported for other packages to see them (and therefore, unmarshal/decode into them): https://tour.golang.org/basics/3
You can use struct tags to map Go field names to JSON keys as well:
type Weather struct {
Name string `json:"name"`
}
... and for the future, you can use https://mholt.github.io/json-to-go/ to auto-generate Go structs from JSON.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论