简体   繁体   English

如何使用Go将JSON文件解析为结构

[英]How Do I Parse a JSON file into a struct with Go

I'm trying to configure my Go program by creating a JSON file and parsing it into a struct: 我正在尝试通过创建JSON文件并将其解析为结构来配置我的Go程序:

var settings struct {
    serverMode bool
    sourceDir  string
    targetDir  string
}

func main() {

    // then config file settings

    configFile, err := os.Open("config.json")
    if err != nil {
        printError("opening config file", err.Error())
    }

    jsonParser := json.NewDecoder(configFile)
    if err = jsonParser.Decode(&settings); err != nil {
        printError("parsing config file", err.Error())
    }

    fmt.Printf("%v %s %s", settings.serverMode, settings.sourceDir, settings.targetDir)
    return
}

The config.json file: config.json文件:

{
    "serverMode": true,
    "sourceDir": ".",
    "targetDir": "."
}

The Program compiles and runs without any errors, but the print statement outputs: 本程序编译并运行没有任何错误,但print语句输出:

false  

(false and two empty strings) (假和两个空字符串)

I've also tried with json.Unmarshal(..) but had the same result. 我也试过json.Unmarshal(..)但结果相同。

How do I parse the JSON in a way that fills the struct values? 如何以填充结构值的方式解析JSON?

You're not exporting your struct elements. 您没有导出struct元素。 They all begin with a lower case letter. 它们都以小写字母开头。

var settings struct {
    ServerMode bool `json:"serverMode"`
    SourceDir  string `json:"sourceDir"`
    TargetDir  string `json:"targetDir"`
}

Make the first letter of your stuct elements upper case to export them. 使你的stuct元素的第一个字母大写以导出它们。 The JSON encoder/decoder wont use struct elements which are not exported. JSON编码器/解码器不会使用未导出的struct元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM