0

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
J.Done
  • 2,783
  • 9
  • 31
  • 58

2 Answers2

1

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

file, err := ioutil.ReadFile("./col.conf")
if err != nil {
    fmt.Printf("File error: %v\n", err)
    os.Exit(1)
}
cfg := Config{}
json.Unmarshal(file, &cfg)
Oliver
  • 11,857
  • 2
  • 36
  • 42
1

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\n", err)
        os.Exit(1)
    }
    cfg := Config{}
    json.Unmarshal(file, &cfg.colInfos)
    fmt.Println(cfg.colInfos[0])
}
AnkurJat
  • 404
  • 3
  • 9