2014-03-28 47 views
1

毫無疑問,快速簡單的問題,但讓我難以置信的問題。將多維JSON文件映射到Go結構

Sophie.conf

{ 
    "host": { 
     "domain": "localhost", 
     "port": 5000 
    } 
} 

main.go

... 

type Config struct { 
    domain string `json:"host.domain"` 
    port int `json:"host.port"` 
} 

... 

func loadConfig() { 
    buffer, _ := ioutil.ReadFile(DEFAULT_CONFIG_FILE) 
    fmt.Println(string(buffer)) 
    json.Unmarshal(buffer, &cfg) 
} 

... 

這可能沒有什麼工作,如果我有

fmt.Printf("host: %s:%d\n", cfg.domain, cfg.port) 

輸出是打印:

host: :0 

我該如何正確地做到這一點?謝謝!

+0

您可以像使用[JSON對去(http://mholt.github.io/json-to-go/)的工具,以JSON轉換爲圍棋結構。 – Matt

+0

@Matt這是一個有用的工具,但我想看看它是如何正確完成的,而不是讓工具爲我做。 –

+0

這很好。但是一旦你開始使用更大的JSON結構,那麼一次只輸出一個字段的結構定義變得不必要繁瑣和重複。 – Matt

回答

3

在你的情況下,你應該聲明外Config結構。在它裏面你應該定義Host字段,在我的例子中它是匿名結構,但是你可以將它作爲顯式結構提取。

一個音符 - 你結構的字段應該導出(大寫字母名稱),或json.Unmarshal(或json.Marshal)將無法正確處理數據,你可以嘗試Play Golang上的字段。

http://play.golang.org/p/msu73bwXNb

package main 

import (
    "encoding/json" 
    "fmt" 
) 

const jsonDocument = ` 
{ 
    "host": { 
     "domain": "localhost", 
     "port": 5000 
    } 
} 
` 

type Config struct { 
    Host struct { 
    Domain string 
    Port int 
    } 
} 

func main() { 
    cfg := &Config{} 
    json.Unmarshal([]byte(jsonDocument), cfg) 
    fmt.Printf("host: %s:%d\n", cfg.Host.Domain, cfg.Host.Port) 
}