将多维JSON文件映射到Go结构
毫无疑问,这是一个又快又简单的问题,但它却把我难住了 Sophie.conf将多维JSON文件映射到Go结构,json,struct,go,Json,Struct,Go,毫无疑问,这是一个又快又简单的问题,但它却把我难住了 Sophie.conf { "host": { "domain": "localhost", "port": 5000 } } main.go ... type Config struct { domain string `json:"host.domain"` port int `json:"host.port"` } ... func loadConfig(
{
"host": {
"domain": "localhost",
"port": 5000
}
}
main.go
...
type Config struct {
domain string `json:"host.domain"`
port int `json:"host.port"`
}
...
func loadConfig() {
buffer, _ := ioutil.ReadFile(DEFAULT_CONFIG_FILE)
fmt.Println(string(buffer))
json.Unmarshal(buffer, &cfg)
}
...
但如果我打印的是
fmt.Printf("host: %s:%d\n", cfg.domain, cfg.port)
输出为:
host: :0
我该如何正确地做到这一点?谢谢 在您的情况下,应该声明outer
Config
struct。在它里面,您应该定义Host
字段,在我的示例中,它是匿名结构,但您可以将其提取为显式结构
一个注意事项-您应该导出结构的字段(大写名称),或者json.Unmarshal
(或者json.Marshal
)将无法正确处理数据,您可以在Play Golang上试验字段
您可以使用类似于将JSON转换为Go结构的工具。@Matt这是一个有用的工具,但我想看看它是如何正确完成的,而不是让一个工具为我完成。这很好。但是一旦你开始使用更大的JSON结构,一次键入一个字段的结构定义就会变得不必要的单调和重复。当然,因此我说这是一个有用的工具。也许我也应该感谢你!我迟来的感谢。
package main
import (
"encoding/json"
"fmt"
)
const jsonDocument = `
{
"host": {
"domain": "localhost",
"port": 5000
}
}
`
type Config struct {
Host struct {
Domain string
Port int
}
}
func main() {
cfg := &Config{}
json.Unmarshal([]byte(jsonDocument), cfg)
fmt.Printf("host: %s:%d\n", cfg.Host.Domain, cfg.Host.Port)
}