2017-10-15 19:30
浏览 66


I'm using the Decoder from package encoding/json to decode a JSON configuration file into a struct. The field names have a different case (lowercase first character in struct because of visibility concerns) in the file and struct so I'm using struct field tags as described in the documentation. The Problem is that Decoder seems to ignore these tags and the struct fields are empty. Any ideas what's wrong with my code?


    "DataSourceName": "simple-blog.db"

Config struct

type Config struct {
     dataSourceName string `json:"DataSourceName"`

Loading config

func loadConfig(fileName string) {
    file, err := os.Open(fileName)
    if err != nil {
        log.Fatalf("Opening config file failed: %s", err)
    defer file.Close()

    decoder := json.NewDecoder(file)
    config = &Config{} // Variable config is defined outside
    err = decoder.Decode(config)
    if err != nil {
        log.Fatalf("Decoding config file failed: %s", err)

    log.Print("Configuration successfully loaded")


log.Printf("DataSourceName: %s", config.dataSourceName)


2017/10/15 21:04:11 DB Name: 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanjiangzhi6851 2017-10-15 19:34

    You need to export your dataSourceName field as encoding/json package requires them to be so

    打赏 评论