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

标签 json go

我有以下 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/

相关文章:

javascript - 使用嵌套 json 数据的 d3 热图 : how to create grids

Go DynamoDB Expression Add无法添加到列表

xml - 如何编码和解码具有不规则属性的 XML

google-app-engine - 如何在与 app.yaml 不同的文件夹中上传 Google App Engine (Go) 项目

c# - C# 中的 VDF 到 JSON

python - 将多行 JSON 转换为 python 字典

json - 过滤 RESTEasy json 翻译 - 我不想发送每个字段!

java - 使用 Jackson 将 JSON 多个对象转换为单个 JSON

go - 有没有办法与 golang 中的任何指针对象进行比较?

go - 使用 Gmail API 时,Gmail 界面中的发件人电子邮件很奇怪