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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题