Go: JSON value not parsed? -
i have simple test: http://play.golang.org/p/wy4sn9auky. config parsed json, first string value parsed ok, sec parsed empty string, not.
type config struct { address string "address" debug bool "debug" dburl string "dburl" googleapikey string "google_api_key" } func (cfg *config) read(json_code string) { if e := json.unmarshal([]byte(json_code), cfg); e != nil { log.printf("error json decode: %v", e) } } func main() { var config config config.read(`{ "address": "10.0.0.2:8080", "debug": true, "dburl": "localhost", "google_api_key": "the-key" }`) log.printf("api key %s", config.googleapikey) // <- empty string. why? log.printf("address %v", config.address) }
you're specifying json names incorrectly in struct.
googleapikey string "google_api_key"
should be
googleapikey string `json:"google_api_key"`
the json bundle looks json
header in text. backtick delimits raw string allows include quotes around google_api_key.
http://play.golang.org/p/knxyhzglap
package main import ( "log" "encoding/json" ) type config struct { address string `json:"address"` debug bool `json:"debug"` dburl string `json:"dburl"` googleapikey string `json:"google_api_key"` } func (cfg *config) read(json_code string) { if e := json.unmarshal([]byte(json_code), cfg); e != nil { log.printf("error json decode: %v", e) } } func main() { var config config config.read(`{ "address": "10.0.0.2:8080", "debug": true, "dburl": "localhost", "google_api_key": "the-key" }`) log.printf("api key %s", config.googleapikey) log.printf("address %v", config.address) }
json go
No comments:
Post a Comment