GoLang-创建一个JSON数组和JSON对象

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

douxu3732
douxu3732 预测的结构是什么。每天,您需要使用jsonUnmarshal
接近 3 年之前 回复
doujingdai5521
doujingdai5521 添加了预测的返回类型。每天
接近 3 年之前 回复
dongyuduan1890
dongyuduan1890 谢谢。您不使用PastDayWeather吗?也是预报。每天是(类型*Datablock)。有没有一种方法可以转换为JSON或PastDayWeather?对不起,我是新来的golang
接近 3 年之前 回复

1个回答

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

dongzou1964
dongzou1964 看一下这段代码play.golang.org/p/GFXb5npoGv
接近 3 年之前 回复
doushuichong2589
doushuichong2589 我必须使用天气方法填充jsonTest字段值
接近 3 年之前 回复
doushao5047
doushao5047 没错,唯一的事情就是我必须构建jsonTest。 比方说,我有一种称为“天气”的方法,我通过执行weather.temperature从天气中获取信息。
接近 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问