【问题标题】:Read json file value in Go [duplicate]在Go中读取json文件值[重复]
【发布时间】:2017-09-05 01:20:37
【问题描述】:

我有一个配置文件。我想从该文件中获取特定值。这是我的代码:

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

【问题讨论】:

    标签: json go


    【解决方案1】:

    你需要exportConfiguration.domain字段,这样json包才能看到。

    将域字段重命名为域:

    type Configuration struct {
      Domain string
    }
    

    如果json名称与字段名称不同,您也可以明确指定:

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

    【讨论】:

      猜你喜欢
      • 2021-02-25
      • 1970-01-01
      • 2013-07-22
      • 2018-01-07
      • 1970-01-01
      • 2023-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多