Golang json解码返回空

时间:2018-04-17 17:57:15

标签: json go

有人可以向我解释为什么这段代码无法正确解码json:

package main
import (
    "fmt"
    "os"
    "log"
    "encoding/json"
)

type Config struct {
    mongoConnectionString string `json:"database"`
    Elastic struct{
        main string `json:"main"`
        log string `json:"log"`
    } `json:"elastic"`
    logFilePath  string `json:"logfile"`
}


func main(){ 
    loadConfiguration("./config.json")
}

func loadConfiguration(file string){
    var configuration Config

    configFile, err := os.Open(file); if err != nil {
        log.Panic("Could not open", file)
    }
    defer configFile.Close()

    if err := json.NewDecoder(configFile).Decode(&configuration); err != nil {
            log.Panic("./config.json is currupted")
    }

    fmt.Print(configuration.logFilePath)
}

Json数据:

{
  "database": "localhost",
  "elastic": {
    "main": "test",
    "log": "test"
  },
  "logfile": "./logs/log.log"
}

执行此程序将导致配置为空.logFilePath

我缺少什么?

由于

1 个答案:

答案 0 :(得分:2)

要使json包从go中的json正确解码,必须在结构定义中导出(大写)字段。

Config更改为:

type Config struct {
    MongoConnectionString string `json:"database"`
    Elastic struct{
        Main string `json:"main"`
        Log string `json:"log"`
    } `json:"elastic"`
    LogFilePath  string `json:"logfile"`
}

将使所有字段正确反序列化。

相关问题