ken*_*ire 1 json go unmarshalling
如何使用 Unmarshal 读取包含两个不同对象的 JSON 文件?
这是JSON文件对应的结构。
{
"mysql": {
"address": "127.0.0.1",
"port": "3306",
"user": "user",
"password": "password",
"database": "database"
},
"postgres": {
"address": "127.0.0.2",
"port": "3306",
"user": "user2",
"password": "password2",
"database": "database2"
}
}
Run Code Online (Sandbox Code Playgroud)
{
"mysql": {
"address": "127.0.0.1",
"port": "3306",
"user": "user",
"password": "password",
"database": "database"
},
"postgres": {
"address": "127.0.0.2",
"port": "3306",
"user": "user2",
"password": "password2",
"database": "database2"
}
}
Run Code Online (Sandbox Code Playgroud)
为此,您需要将MysqlandPostgres结构包装成一个Configuration结构,然后将其传递给 Unmarshal 函数:
type Configuration struct {
Mysql Mysql
Postgres Postgres
}
func main() {
content, err := ioutil.ReadFile(confPath)
var conf Configuration
err = json.Unmarshal(content, &conf)
}
Run Code Online (Sandbox Code Playgroud)
查看完整的工作示例:https ://play.golang.org./p/7CtALgsjK3
希望这会帮助一些人。