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 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,