如何从Go中的一个文件中读取多个JSON对象

时间:2017-08-29 07:17:03

标签: json go unmarshalling

如何使用Unmarshal读取有两个不同对象的JSON文件?

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
}

2 个答案:

答案 0 :(得分:4)

为此,您需要将MysqlPostgres结构包装到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"
  }
}`