douhuan7862 2017-08-28 23:17
浏览 444
已采纳

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

How can I read a JSON file where there is two different objects using Unmarshal ?

JSON example:

This is the structure corresponding to the JSON file.

{
  "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"
  }
}

Code snippet:

type Database struct {
    Address  string
    Port     string
    User     string
    Password string
    Database string
}
type Mysql struct {
    Database
}
type Postgres struct {
    Database
}

展开全部

  • 写回答

2条回答 默认 最新

  • drlndkhib08556095 2017-08-28 23:17
    关注

    To do this, you need to wrap the Mysql and Postgres structure into a Configuration structure then pass it to Unmarshal function:

    type Configuration struct {
        Mysql    Mysql
        Postgres Postgres
    }
    
    func main() {
        content, err := ioutil.ReadFile(confPath)
        var conf Configuration
        err = json.Unmarshal(content, &conf)
    }
    

    See full working example: https://play.golang.org./p/7CtALgsjK3

    Hope this will help some people.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部