go解析json

[gdut17@localhost http]$ go run getjson.go 
{[{{WS0E9D8WN298 广州 CN 广州,广州,广东,中国 Asia/Shanghai +08:00} {阴 9 29} 2020-10-15T14:30:00+08:00}]}

地点:广州,温度:29,天气:阴,时间:2020-10-15T14:30:00+08:00
[gdut17@localhost http]$ 

package main
import (
	"fmt"
	"net/http"
	"encoding/json"
	"io/ioutil"
)

func main() {
	url := "http://api.seniverse.com/v3/weather/now.json?key=0pyd8z7jouficcil&location=guangzhou&language=zh-Hans&unit=c"
	
	GetJson(url) 


	//test()
}

func GetJson(url string) {
	res, err := http.Get(url)
	if err != nil {
		fmt.Println("get err")
		return 
	}
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println("read err")
		return 
	}
	jsonByte := []byte(body)
	//res := Result{}
	var w Weather
	err = json.Unmarshal(jsonByte, &w)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(w)
	fmt.Printf("\n地点:%s,温度:%s,天气:%s,时间:%s\n",
		w.Results[0].Location.Name,
		w.Results[0].Now.Temperature,
		w.Results[0].Now.Text,
		w.Results[0].Last_update)
	//fmt.Printf("%T\n",w)
	//fmt.Printf("%T %s\n",body, body)
}

type Locat struct {
	Id string `json:"id"`
	Name string `json:"name"`
	Country string `json:"country"`
	Path string `json:"path"`
	Timezone string `json:"timezone"`
	Timezone_offset string `json:"timezone_offset"`
}
type Wea struct {
	Text string `json:"text"`
	Code string `json:"code"`
	Temperature string `json:"temperature"`
}

type Member struct {
    Location Locat `json:"location"`
	Now Wea `json:"now"`	
	Last_update string `json:"last_update"`
}

type Weather struct {
    Results []Member `json:member`
}

func test() {
	jsonString := `
	{
		"results":
		[
			{	
				"location":
				{
					"id":"WT029G15ETRJ",
					"name":"长沙",
					"country":"CN",
					"path":"长沙,长沙,湖南,中国",
					"timezone":"Asia/Shanghai",
					"timezone_offset":"+08:00"
				},
				"now":
				{
					"text":"小雨",
					"code":"13",
					"temperature":"16"
				},
				"last_update":"2020-10-15T13:50:08+08:00"
			}
		]
	}`
	jsonByte := []byte(jsonString)
	//res := Result{}
	var res Weather
	err := json.Unmarshal(jsonByte, &res)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(res)
	fmt.Printf("%T\n",res)
	//fmt.Printf("%+v\n",res)
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值