doyrte8419
doyrte8419
2017-07-18 02:35

加载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 duankeng1911 4年前

    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])
    }
    
    点赞 评论 复制链接分享
  • dtot74529 dtot74529 4年前

    You should use json.Unmarshal() to populate your config struct.

    file, err := ioutil.ReadFile("./col.conf")
    if err != nil {
        fmt.Printf("File error: %v
    ", err)
        os.Exit(1)
    }
    cfg := Config{}
    json.Unmarshal(file, &cfg)
    
    点赞 评论 复制链接分享