gpt4 book ai didi

当它们应该是值时返回为 0 的 JSON 整数

转载 作者:行者123 更新时间:2023-12-01 22:38:51 26 4
gpt4 key购买 nike

我有以下 JSON 文件,正在尝试解析它。

{
"coord":
{
"lon":-121.31,
"lat":38.7},
"weather":[
{
"id":800,
"main":"Clear",
"description":"clear sky",
"icon":"01d"}
],
"base":"stations",
"main":
{
"temp":73.26,
"pressure":1018,
"humidity":17,
"temp_min":68,
"temp_max":77},

预期的输出是:
当前温度:73
今日低点:68
今日高点:77
当前湿度:17%

但它反而返回:
当前温度:0
今日低点:0
今日高点:0
当前湿度:0%

这是我试图用来获得所需返回的代码:

package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strconv"
)


type Daily struct {
Currenttemp int `json:"temp"`
Mintemp int `json:"temp_min"`
Maxtemp int `json:"temp_max"`
Humidity int `json:"humidity"`
}


func main() {
jsonFile, err := os.Open("jsontest1.json")
if err != nil {
fmt.Println(err)
}

fmt.Println("Successfully Opened jsontest1.json")

defer jsonFile.Close()

byteValue, _ := ioutil.ReadAll(jsonFile)

var daily Daily

json.Unmarshal(byteValue, &daily)


fmt.Println("Current Temperature:"+strconv.Itoa(daily.Currenttemp))
fmt.Println("Today's Low:"+strconv.Itoa(daily.Mintemp))
fmt.Println("Today's High:"+strconv.Itoa(daily.Maxtemp))
fmt.Println("Current Humidity:"+strconv.Itoa(daily.Humidity)+"%")


}

我错过了什么?

最佳答案

首先,您的示例 JSON 输入格式错误:它以 }, 结尾何时应该以 }} 结尾.这会导致 json.Unmarshal返回错误:

unexpected EOF

解决这个问题会导致更多问题,其中许多人已经在评论中指出。例如,您的输入与 struct 的结构不同。 , 和 JSON 数字解码为 float64 ,而不是 int .其中一个值 - 带有键 "temp" 的值——是 73.26 ,它不是整数。

我有点不喜欢默默地忽略未知领域,所以我喜欢使用 json.Decoder其中未知字段是不允许的。这有助于确保您没有通过使用错误的标签或错误级别的标签来搞砸数据结构,因为当您这样做时,您只会将所有缺失的字段都归零。所以我喜欢添加一个“忽略”解码器来显式忽略字段:
type ignored [0]byte
func (i *ignored) UnmarshalJSON([]byte) error {
return nil
}

然后您可以声明 ignored 类型的字段但仍然给他们 json 标签(尽管匹配字段名称的默认值往往就足够了):
type overall struct {
Coord ignored
Weather ignored
Base ignored
Main Daily
}

如果您真的想直接解码为整数类型,则需要再次花哨,我在示例中就是这样做的。直接解码到 float64 可能更明智尽管。如果你这样做——使用 float64并且不要添加特殊类型来忽略某些字段——您可以放弃使用 json.NewDecoder .

您可以变得更漂亮,并使用指针来判断您的字段是否已填写,但我在示例中没有这样做。我剪掉了文件读取(以及读取调用中缺少错误检查)并改用硬编码输入数据。可以解码的最终版本是 here on the Go Playground .

关于当它们应该是值时返回为 0 的 JSON 整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58676589/

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