doyrte8419 2017-07-18 02:35
浏览 106
已采纳

加载json数组配置

I would like to load json configuration file to go lang app. Configuration data is array since it needs to be dynamically set.

[ { "key": "A", "data": [1, 2, 3]}, { "key": "B", "data": [1, 2]}, { "key": "C", "data": [1, 3]} ]

And tried to load like this.

package main

import (
    "flag"
    "fmt"
    "os"
    "encoding/json"
)

type ColInfo struct {
    key     string  `json:"key"`
    col     []int   `json:"data"`
}
type Config struct {
    colInfos    []ColInfo
}

func main() {
    flag.Parse()
    file, _ := os.Open("col.conf")
    decoder := json.Marshal(file)
    configuration := Config{}
    if err := decoder.Decode(&configuration); err != nil {
        fmt.Println(err)
    }
    println( configuration.colInfos[0].key)
}

Here is error I've got

./test2.go:23: multiple-value json.Marshal() in single-value context

What am i wrong with this?

  • 写回答

2条回答 默认 最新

  • duankeng1911 2017-07-18 06:39
    关注

    You need to change your "ColInfo" struct keys so that "json" package can read them. I'm attaching a working code snippet

    package main
    
    import (
        "encoding/json"
        "fmt"
        "io/ioutil"
        "os"
    )
    
    type ColInfo struct {
        Key string `json:"key"`
        Col []int  `json:"data"`
    }
    type Config struct {
        colInfos []ColInfo
    }
    
    func main() {
        file, err := ioutil.ReadFile("configurtaion.txt")
        if err != nil {
            fmt.Printf("File error: %v
    ", err)
            os.Exit(1)
        }
        cfg := Config{}
        json.Unmarshal(file, &cfg.colInfos)
        fmt.Println(cfg.colInfos[0])
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 非科班怎么跑代码?如何导数据和调参
  • ¥15 福州市的全人群死因监测点死亡原因报表
  • ¥15 打开powerpont询问是否安装officeplus不小心点了不安装以后再也不提示是否安装了
  • ¥15 Altair EDEM中生成一个颗粒,并且各个方向没有初始速度
  • ¥15 系统2008r2 装机配置推荐一下
  • ¥15 悬赏Python-playwright部署在centos7上
  • ¥15 psoc creator软件有没有人能远程安装啊
  • ¥15 快速扫描算法求解Eikonal方程咨询
  • ¥20 我的是道格手机,重置后屏幕右上角出现红色字的未写入tee key 和未写入google key请问怎么去掉啊
  • ¥15 校内二手商品转让网站