Read json file value in Go

huangapple go评论71阅读模式
英文:

Read json file value in Go

问题

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

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

英文:

I have a config file. I want to get specific value from that file. Here is my code :

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"
}

But the problem is it always print empty line, not the value localhost:8000 I am expecting.

答案1

得分: 1

你需要导出 Configuration.domain 字段,以便 json 包可以看到它。

将 domain 字段重命名为 Domain:

type Configuration struct {
  Domain string
}

如果 json 名称与字段名不同,你还可以显式指定 json 名称:

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

You need to export Configuration.domain field so that json package can see it.

Rename the domain field to Domain:

type Configuration struct {
  Domain string
}

You can also specify json name explicitly if it differs from field name:

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

huangapple
  • 本文由 发表于 2017年4月10日 13:40:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/43315692.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定