英文:
parsing json from a file in go
问题
config.json
{
"admins": [
"AdminA",
"AdminB"
],
"apikey": "apikey"
}
main.go
package main
import (
"os"
"fmt"
"encoding/json"
)
type MainConfiguration struct {
admins []string `json:"admins"`
apikey string `json:"apikey"`
}
func ParseConf() *MainConfiguration {
f, _ := os.Open("config.json")
defer f.Close()
d := json.NewDecoder(f)
m := &MainConfiguration{}
d.Decode(m)
return m
}
func main() {
conf := ParseConf()
fmt.Printf("%s", conf)
}
在查找了所有可能的解决方法后,我得到的结果是:
&{[] }
这里有什么问题,为什么是空的?这个问题很基础,我只是从其他地方复制/粘贴过来的,虽然这可能很常见,但我没有找到针对这个特定问题的答案。
英文:
config.json
{
"admins": [
"AdminA",
"AdminB"
],
"apikey": "apikey"
}
main.go
package main
import (
"os"
"fmt"
"encoding/json"
)
type MainConfiguration struct {
admins []string `json:"admins"`
apikey string `json:"apikey"`
}
func ParseConf() *MainConfiguration {
f, _ := os.Open("config.json")
defer f.Close()
d := json.NewDecoder(f)
m := &MainConfiguration{}
d.Decode(m)
return m
}
func main() {
conf := ParseConf()
fmt.Printf("%s", conf)
}
After looking for everything I could to fix this all I get is:
&{[] }
Whats wrong here, and why is this empty? Its basic and I've basically just copy/pasted from elsewhere and while this may be common, I'm not finding answers to this specific question.
答案1
得分: 3
你需要将MainConfiguration中的字段设置为公共的(注意首字母大写):
type MainConfiguration struct {
Admins []string `json:"admins"`
Apikey string `json:"apikey"`
}
英文:
You need to make fields in MainConfiguration public (note first capital letter):
type MainConfiguration struct {
Admins []string `json:"admins"`
Apikey string `json:"apikey"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论