duai3681 2018-04-17 17:57
浏览 54
已采纳

Golang json解码返回空[重复]

This question already has an answer here:

Can some one please explain to me why this code fail to decode json properly:

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 data:

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

The execution of this program will result in empty configuration.logFilePath

What am i missing?

Thanks

</div>
  • 写回答

1条回答 默认 最新

  • douqiju2520 2018-04-17 18:11
    关注

    For the json package to properly decode from json in go, fields must be exported (capitalized) within the struct definition.

    Changing Config to:

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

    will make all fields deserialize correctly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料