parsing json from a file in go

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

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

huangapple
  • 本文由 发表于 2014年4月4日 01:01:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/22844279.html
匿名

发表评论

匿名网友

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

确定