2017-07-18 45 views
0

我想加載json配置文件去lang應用程序。 配置數據是數組,因爲它需要動態設置。加載json數組配置

[ { 「鍵」: 「A」, 「數據」:[1,2,3]}, { 「鍵」: 「B」, 「數據」:[1,2]} , {「key」:「C」,「data」:[1,3]}]

並試圖以這種方式加載。

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) 
} 

這是錯誤我有

./test2.go:23:多值json.Marshal()的單值上下文

我是什麼這個錯誤?

+0

你告訴我們,你看到的錯誤是什麼?首先看看打開文件時你忽略了一個錯誤 –

+0

在下面添加了錯誤消息。 –

+0

[Go json.Marshal(struct)可能重複返回「{}」](https://stackoverflow.com/questions/26327391/go-json-marshalstruct-returns) –

回答

1

您需要更改您的「ColInfo」結構鍵,以便「json」包可以讀取它們。我附上一個工作代碼片段

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]) 
} 
1

您應該使用json.Unmarshal()填充您的配置結構。

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)