-1

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

wolter
  • 21
  • 3

1 Answers1

9

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.

Brent Dimmig
  • 156
  • 5