解组JSON返回空结构

Ved*_*ran 0 json go unmarshalling

这是我的JSON文件:

{
    "database": {
        "dialect": "mysql"
        "host": "localhost",
        "user": "root",
        "pass": "",
        "name": "sws"
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

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)
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

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

Type: config.ConfigType%
Run Code Online (Sandbox Code Playgroud)

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

icz*_*cza 5

错误不会慷慨地退给您,除非您想知道为什么您的应用无法正常工作。不要遗漏错误!ioutil.ReadAll()返回错误。json.Unmarshal()返回错误。检查那些!

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

panic: invalid character '"' after object key:value pair
Run Code Online (Sandbox Code Playgroud)

Go Playground上尝试一下。

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

Conf: {{mysql localhost root  sws}}
Content: 
 localhost 
Type: main.ConfigType
Run Code Online (Sandbox Code Playgroud)