2017-04-10 65 views
-2

我有一個配置文件。我想從該文件中獲得特定的值。這裏是我的代碼:在Go中閱讀json文件的值

package main 

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

type Configuration struct { 
    consumer_key string 
    consumer_secret string 
    access_token string 
    access_token_secret string 
    db_name string 
    db_user string 
    db_password string 
    secret_key string 
    fb_page string 
    fb_page_token string 
    domain string 
} 

func main() { 
    file, _ := os.Open("./config.json") 
    decoder := json.NewDecoder(file) 
    configuration := Configuration{} 
    error_ := decoder.Decode(&configuration) 
    fmt.Println(configuration.domain) 
} 

config.json

{ 
    "consumer_key": "", 
    "consumer_secret": "", 
    "access_token": "", 
    "access_token_secret": "", 
    "db_name": "", 
    "db_user": "", 
    "db_password": "", 
    "secret_key": "", 
    "fb_page": "", 
    "fb_page_token": "", 
    "domain": "localhost:8000" 
} 

但問題是,它總是打印空行,而不是價值localhost:8000我期待。

回答

1

您需要export Configuration.domain字段,以便json包可以看到它。

域字段重命名爲域:

type Configuration struct { 
    Domain string 
} 

您也可以明確指定json的名稱,如果它的字段名稱不同:

type Configuration struct { 
    Domain string `json:"domain_name"` 
}