I am developing an app for GoLang. the app is getting JSON data back from a third party
I do not see how to create the json object and append it to a json array. What's happening is that I have a loop and each element received.
below is the code:
type PastWeekWeatherArray struct {
PastWeekWeather []PastDayWeather `json:"array"`
}
type PastDayWeather struct {
DayWeather string `json:"day"`
}
func get_weather(ctx context.Context, place string, date string) (string, error){
var msg PastWeekWeatherArray
client := darksky.New(apiKey)
for j:= 0; j < 7; j++ {
forecast, err := client.get_data(j)
if(err != nil) {
fmt.Println(err.Error())
return "",err
}
// forecast.Daily
}
the data is contained in the forecast.Daily. this response need to be stored in 'PastDayWeather', json obect and then append to the PastWeekWeatherArray
forecast.Daily
is returning a (type *Datablock), I would like to cast it or make it a JSON and then insert in the JSON Array.
Regards
if I understood right the code below can help you.
package main
import (
"fmt"
"encoding/json"
)
type PastWeekWeatherArray struct {
PastWeekWeather []PastDayWeather `json:"pastWeekWeather"`
}
type PastDayWeather struct {
DayWeather string `json:"dayWeather"`
}
var (
jsonTest = `{
"pastWeekWeather": [
{"dayWeather":"10"},
{"dayWeather":"15"}
]
}`
)
func main() {
array := PastWeekWeatherArray{make([]PastDayWeather, 0)}
err := json.Unmarshal([]byte(jsonTest), &array)
fmt.Println("Error: ", err)
for _, v := range array.PastWeekWeather{
fmt.Println("Day: ", v.DayWeather)
}
}
Pay attention that the tag json like json:"pastWeekWeather"
needs to have the same name that I put in the variable name in jsonTest. Also you can run the code here