gpt4 book ai didi

json - 解码 JSON 返回空结构

转载 作者:IT王子 更新时间:2023-10-29 02:27:19 43 4
gpt4 key购买 nike

这是我的 JSON 文件:

{
"database": {
"dialect": "mysql"
"host": "localhost",
"user": "root",
"pass": "",
"name": "sws"
}
}

这是我的代码:

package config

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

type ConfigType struct {
Database DatabaseType `json:"database"`
}

type DatabaseType struct {
Dialect string `json:"dialect"`
Host string `json:"host"`
User string `json:"user"`
Pass string `json:"pass"`
Name string `json:"name"`
}

func Config() {
file, err := os.Open("./config/config.json")
if err != nil {
log.Fatal(err)
}
defer file.Close()

fileBytes, _ := ioutil.ReadAll(file)

var Conf ConfigType
json.Unmarshal(fileBytes, &Conf)

fmt.Printf("File content:\n%v", string(fileBytes))
fmt.Printf("Conf: %v\n", Conf)
fmt.Printf("Content: \n %v \nType: %T", Conf.Database.Host, Conf)
}

这是输出:

File content:
{
"database": {
"dialect": "mysql"
"host": "localhost",
"user": "root",
"pass": "",
"name": "sws"
}
}
Conf: {{ }}
Content:

Type: config.ConfigType%

包被导入到 main 并且只执行 Config 函数。我看过很多类似的问题,看起来我的代码几乎与答案中的代码完全相同,但我无法让我的代码正常工作。

最佳答案

除非您想对您的应用程序无法运行的原因一无所知,否则不会优雅地返回给您以忽略错误。不要遗漏错误! ioutil.ReadAll() 返回一个错误。 json.Unmarshal() 返回一个错误。一定要检查那些!

如果您添加错误检查,json.Unmarshal() 返回:

panic: invalid character '"' after object key:value pair

Go Playground 上试试这个.

您输入的 JSON 无效。 "dialect" 行中缺少逗号。添加缺少的逗号(在 Go Playground 上尝试):

Conf: {{mysql localhost root  sws}}
Content:
localhost
Type: main.ConfigType

关于json - 解码 JSON 返回空结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47700708/

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