douhuan7862 2017-08-29 07: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-29 07: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条)

报告相同问题?

悬赏问题

  • ¥50 adb连接不到手机是怎么回事?
  • ¥20 抓取数据时发生错误: get_mooncake_data() missing 1 required positional argument: 'driver'的问题,怎么改出正确的爬虫代码?
  • ¥15 vs2022无法联网
  • ¥15 TCP的客户端和服务器的互联
  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,