简体   繁体   English

转到:JSON值未解析?

[英]Go: JSON value not parsed?

I have very simple test: http://play.golang.org/p/wY4sN9AUky . 我有一个非常简单的测试: http : //play.golang.org/p/wY4sN9AUky Config parsed from JSON, first string value parsed OK, but second parsed to empty string, but it is not. 从JSON解析配置,第一个字符串值解析为OK,但是第二个解析为空字符串,但不是。

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 your JSON names incorrectly in the struct. 您在结构中错误地指定了JSON名称。

GoogleApiKey string "google_api_key"

should be 应该

GoogleApiKey string `json:"google_api_key"`

The JSON package looks for the json header in the text. JSON包在文本中查找json标头。 The backtick delimits a raw string which allows us to include the quotes around google_api_key. 反引号分隔了原始字符串,使我们可以在google_api_key周围加上引号。

http://play.golang.org/p/KNxYhzGLAp 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM