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条)

报告相同问题?

悬赏问题

  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)