Search code examples
jsongostructconfigdecoding

JSON Decoder ignores struct field tags?


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?

config.json

{
    "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")
}

Usage

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

Output

2017/10/15 21:04:11 DB Name: 

Solution

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