gpt4 book ai didi

json - 在 Golang 中解析 Json

转载 作者:IT王子 更新时间:2023-10-29 02:24:18 26 4
gpt4 key购买 nike

一直在尝试使用 go 解析此 json 文件以获取最低和最高温度
给定城市的。

{
"data": {
"current_condition": [
{
"cloudcover": "25",
"humidity": "56",
"observation_time": "01:33 PM",
"precipMM": "0.0",
"pressure": "1016",
"temp_C": "20",
"temp_F": "68",
"visibility": "10",
"weatherCode": "116",
"weatherDesc": [
{
"value": "Partly Cloudy"
}
],
"weatherIconUrl": [
{
"value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png"
}
],
"winddir16Point": "SSW",
"winddirDegree": "210",
"windspeedKmph": "7",
"windspeedMiles": "4"
}
],
"request": [
{
"query": "London, United Kingdom",
"type": "City"
}
],
"weather": [
{
"date": "2014-09-07",
"precipMM": "0.0",
"tempMaxC": "23",
"tempMaxF": "74",
"tempMinC": "10",
"tempMinF": "49",
"weatherCode": "119",
"weatherDesc": [
{
"value": "Cloudy"
}
],
"weatherIconUrl": [
{
"value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0003_white_cloud.png"
}
],
"winddir16Point": "N",
"winddirDegree": "355",
"winddirection": "N",
"windspeedKmph": "9",
"windspeedMiles": "6"
}
]
}
}

已成功使用结构和解码 json 字符串。
现在我想尝试使用 map ,例如 map[string]interface{}

如果u是map[string]interface{}类型,json解析成u,
u["data"].(map[string]interface{})["weather"]
给出值

http://api.worldweatheronline.com/free/v1/weather.ashx?q=london&format=json&num_of_days=1&key=8c52bb73c5f6160f5f3aa535d22184638372d22b [map[tempMaxC:23 tempMaxF:74 tempMinC:10 tempMinF:49 winddirection:N windspeedMiles:6 date:2014-09-07 precipMM:0.0 weatherCode:119 winddir16Point:N winddirDegree:355 weatherDesc:[map[value:Cloudy]] weatherIconUrl:[map[value:http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0003_white_cloud.png]] windspeedKmph:9]]

u["data"].(map[string]interface{})["weather"].(map[string]interface{})["tempMinC"],
给我一个 panic: interface conversion: interface is []interface {}, not map[string]interface {}

谁能解释一下发生了什么?

最佳答案

u["data"].(map[string]interface{})["weather"] 是 map 的一部分,而不是 map ,因此您必须执行以下操作:

maps, ok := u["data"].(map[string]interface{})["weather"].([]interface{})
if !ok {
panic("bad json")
}
for _, m := range maps {
if m, ok := m.(map[string]interface{}); ok {
fmt.Println(m["tempMinC"])
}
}

在您的 JSON 示例中,weather 是一个对象数组,因此在 Go 中这会转换为一片 map ([]map[string]interface{})。

关于json - 在 Golang 中解析 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25711058/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com