从json.Decoder中获取键和值。

huangapple go评论78阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2016年2月16日 23:25:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/35436424.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定