如何使用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"
}
}
type Database struct {
Address string
Port string
User string
Password string
Database string
}
type Mysql struct {
Database
}
type Postgres struct {
Database
}
答案 0 :(得分:4)
为此,您需要将Mysql
和Postgres
结构包装到Configuration
结构中,然后将其传递给Unmarshal函数:
type Configuration struct {
Mysql Mysql
Postgres Postgres
}
func main() {
content, err := ioutil.ReadFile(confPath)
var conf Configuration
err = json.Unmarshal(content, &conf)
}
请参阅完整的工作示例:https://play.golang.org./p/7CtALgsjK3
希望这会对某些人有所帮助。
答案 1 :(得分:1)
另一种方式:
react-google-maps
尝试this:
m := make(map[string]Db)
err := json.Unmarshal([]byte(input), &m)
输出:
package main
import (
"encoding/json"
"fmt"
)
func main() {
m := make(map[string]Db)
err := json.Unmarshal([]byte(input), &m)
if err != nil {
fmt.Println(err)
}
fmt.Println(m)
}
type Db struct {
Address string
Port string
User string
Password string
Database string
}
const input = `{
"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"
}
}`
即使这适合你:
map[mysql:{127.0.0.1 3306 user password database} postgres:{127.0.0.2 3306 user2 password2 database2}]
尝试this:
m := make(map[string]map[string]string)
err := json.Unmarshal([]byte(input), &m)
输出:
package main
import (
"encoding/json"
"fmt"
)
func main() {
m := make(map[string]map[string]string)
err := json.Unmarshal([]byte(input), &m)
if err != nil {
fmt.Println(err)
}
fmt.Println(m)
}
const input = `{
"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"
}
}`