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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16681003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:47:51  来源:igfitidea点击:

How Do I Parse a JSON file into a struct with Go

jsonparsinggo

提问by Charles

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:

程序编译和运行没有任何错误,但打印语句输出:

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?

回答by Daniel

You're not exporting your struct elements. 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. The JSON encoder/decoder wont use struct elements which are not exported.

将 stuct 元素的第一个字母设为大写以导出它们。JSON 编码器/解码器不会使用未导出的结构元素。