将 JSON 数组解组为 Go 结构体(数组位于 JSON 字符串的中间)

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

unmarshal json array into go struct (array is in the middle of the JSON string

问题

我是你的中文翻译助手,以下是你提供的代码的翻译:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. )
  9. // WeatherData 结构体用于存储从 API 调用中获取的数据
  10. type WeatherData struct {
  11. Wind Wind
  12. Sys Sys
  13. // Weather Weather
  14. Name string `json:"name"`
  15. }
  16. ////////////// 在解组这个结构体时出现错误 ///////////
  17. // Weather 提供基本的天气信息
  18. // type Weather struct {
  19. // ID int `json:"id"`
  20. // Descrip string `json:"description"`
  21. // Icon string `json:"icon"`
  22. // }
  23. /////////////////////////////////////////////////////////
  24. // Sys 包括日出、日落、国家等信息
  25. type Sys struct {
  26. Country string `json:"country"`
  27. }
  28. // Wind 结构体用于获取具体的风力特征
  29. type Wind struct {
  30. Speed float64 `json:"speed"`
  31. Degree float64 `json:"deg"`
  32. Gust float64 `json:"gust"`
  33. }
  34. func main() {
  35. res, getErr := http.Get("http://api.openweathermap.org/data/2.5/weather?zip=REMOVED,us&appid=REMOVEDBUTWILLPOSTJSONData")
  36. if getErr != nil {
  37. log.Fatalln("http.Get error:", getErr)
  38. }
  39. defer res.Body.Close()
  40. body, readErr := ioutil.ReadAll(res.Body)
  41. if readErr != nil {
  42. log.Fatalln("Read Error:", readErr)
  43. }
  44. //////////// 无法解组通过这里的数组 //////////
  45. var data WeatherData
  46. if err := json.Unmarshal(body, &data); err != nil {
  47. panic(err)
  48. }
  49. fmt.Println("Wind gusts:", data.Wind.Gust)
  50. fmt.Println("Wind speed:", data.Wind.Speed)
  51. fmt.Println("Wind degrees:", data.Wind.Degree)
  52. fmt.Println("Country is:", data.Sys.Country)
  53. fmt.Println("City is:", data.Name)
  54. ///////////// 无法访问 Description...或者 Weather 中的任何内容
  55. // fmt.Println("Country is:", data.Weather.Descrip) // 由于该部分位于数组中,无法访问
  56. }

这是你提供的可用的 JSON 数据:

  1. {
  2. "coord": {
  3. "lon": -97.31,
  4. "lat": 32.94
  5. },
  6. "weather": [ // 无法正确访问这里
  7. {
  8. "id": 800,
  9. "main": "Clear",
  10. "description": "clear sky",
  11. "icon": "01d"
  12. }
  13. ],
  14. "base": "stations",
  15. "main": {
  16. "temp": 306.46,
  17. "pressure": 1014,
  18. "humidity": 55,
  19. "temp_min": 306.15,
  20. "temp_max": 307.15
  21. },
  22. "visibility": 16093,
  23. "wind": {
  24. "speed": 5.1,
  25. "deg": 150,
  26. "gust": 7.2
  27. },
  28. "clouds": {
  29. "all": 1
  30. },
  31. "dt": 1499120100,
  32. "sys": {
  33. "type": 1,
  34. "id": 2597,
  35. "message": 0.0225,
  36. "country": "US",
  37. "sunrise": 1499081152,
  38. "sunset": 1499132486
  39. },
  40. "id": 0,
  41. "name": "Fort Worth",
  42. "cod": 200
  43. }

希望对你有帮助!

英文:

I am new to Go. I am working with a weather API. I have commented out the sections that cause the error. I have seen several other links that have a similar problem, however none of them seem to have the array in the middle of the JSON string. I'm sure there is a way to define the struct with a slice. I can't seem to get get the syntax to allow it. Here is where I'm stuck:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. )
  9. // WeatherData struct to collect data from the API call
  10. type WeatherData struct {
  11. Wind Wind
  12. Sys Sys
  13. // Weather Weather
  14. Name string `json:"name"`
  15. }
  16. ////////////// ERROR when unmarshalling this struct /////////
  17. // Weather provides basic weather info
  18. // type Weather struct {
  19. // ID int `json:"id"`
  20. // Descrip string `json:"description"`
  21. // Icon string `json:"icon"`
  22. // }
  23. /////////////////////////////////////////////////////////////
  24. // Sys includes sunrise, sunset, country, etc.
  25. type Sys struct {
  26. Country string `json:"country"`
  27. }
  28. // Wind struct to get specific wind characteristics
  29. type Wind struct {
  30. Speed float64 `json:"speed"`
  31. Degree float64 `json:"deg"`
  32. Gust float64 `json:"gust"`
  33. }
  34. func main() {
  35. res, getErr := http.Get("http://api.openweathermap.org/data/2.5/weather?zip=REMOVED,us&appid=REMOVEDBUTWILLPOSTJSONData")
  36. if getErr != nil {
  37. log.Fatalln("http.Get error: ", getErr)
  38. }
  39. defer res.Body.Close()
  40. body, readErr := ioutil.ReadAll(res.Body)
  41. if readErr != nil {
  42. log.Fatalln("Read Error: ", readErr)
  43. }
  44. //////////// UNABLE TO UNMARSHAL the array that passes through here ////
  45. var data WeatherData
  46. if err := json.Unmarshal(body, &data); err != nil {
  47. panic(err)
  48. }
  49. fmt.Println("Wind gusts: ", data.Wind.Gust)
  50. fmt.Println("Wind speed: ", data.Wind.Speed)
  51. fmt.Println("Wind degrees: ", data.Wind.Degree)
  52. fmt.Println("Country is: ", data.Sys.Country)
  53. fmt.Println("City is: ", data.Name)
  54. ///////////////// CAN'T ACCESS Description...or anything in Weather
  55. // fmt.Println("Country is: ", data.Weather.Descrip) // cannot access due to this portion being inside an array
  56. }
  57. /////////////////THIS IS THE JSON DATA THAT IS AVAILABLE ///////////
  58. {
  59. "coord": {
  60. "lon": -97.31,
  61. "lat": 32.94
  62. },
  63. "weather": [ // CAN'T ACCESS THIS CORRECTLY
  64. {
  65. "id": 800,
  66. "main": "Clear",
  67. "description": "clear sky",
  68. "icon": "01d"
  69. }
  70. ],
  71. "base": "stations",
  72. "main": {
  73. "temp": 306.46,
  74. "pressure": 1014,
  75. "humidity": 55,
  76. "temp_min": 306.15,
  77. "temp_max": 307.15
  78. },
  79. "visibility": 16093,
  80. "wind": {
  81. "speed": 5.1,
  82. "deg": 150,
  83. "gust": 7.2
  84. },
  85. "clouds": {
  86. "all": 1
  87. },
  88. "dt": 1499120100,
  89. "sys": {
  90. "type": 1,
  91. "id": 2597,
  92. "message": 0.0225,
  93. "country": "US",
  94. "sunrise": 1499081152,
  95. "sunset": 1499132486
  96. },
  97. "id": 0,
  98. "name": "Fort Worth",
  99. "cod": 200
  100. }

答案1

得分: 5

你必须在WeatherData中定义Weather结构体的切片。

取消注释Weather结构体,并将WeatherData结构体更新为以下内容。

  1. // WeatherData struct to collect data from the API call
  2. type WeatherData struct {
  3. Wind Wind `json:"wind"`
  4. Sys Sys `json:"sys"`
  5. Weather []Weather `json:"weather"`
  6. Name string `json:"name"`
  7. }

请查看示例代码:https://play.golang.org/p/4KFqRuxcx2

英文:

You have to define slice of Weather struct in WeatherData.

Uncomment Weather struct and update WeatherData struct to following.

  1. // WeatherData struct to collect data from the API call
  2. type WeatherData struct {
  3. Wind Wind `json:"wind"`
  4. Sys Sys `json:"sys"`
  5. Weather []Weather `json:"weather"`
  6. Name string `json:"name"`
  7. }

Please have a look on example code: https://play.golang.org/p/4KFqRuxcx2

huangapple
  • 本文由 发表于 2017年7月4日 08:58:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/44895535.html
匿名

发表评论

匿名网友

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

确定