我一直在尝试通过解组我的 json 文件来提取一些 JSON,但是,我不知道为什么它没有发生。我能够使用viper.AllSettings()但不能通过解组来获取数据。我认为我犯了一个愚蠢的错误,请分享您的想法。github链接是-https: //github.com/parthw/100-days-of-code/tree/main/golang/d6-cobra-viper-continued,代码如下。main.gopackage mainimport ( "fmt" "example.com/cobra-viper/cmd" "github.com/spf13/viper")// Myconfig exampletype Myconfig struct { username string `mapstructure:"username"`}func main() { cmd.Execute() fmt.Println("I can print this ", viper.AllSettings()) var mc Myconfig if err := viper.Unmarshal(&mc); err != nil { fmt.Println(err) } fmt.Println(mc)}在 cmd 目录中使用 cobra CLI 生成的代码:package cmdimport ( "fmt" "os" "github.com/spf13/cobra" homedir "github.com/mitchellh/go-homedir" "github.com/spf13/viper")var ( cfgFile string author string)// Myconfig exampletype Myconfig struct { username string}// rootCmd represents the base command when called without any subcommandsvar rootCmd = &cobra.Command{ Use: "cobra-viper", Short: "A brief description of your application", Long: `A longer description that spans multiple lines and likely containsexamples and usage of using your application. For example:Cobra is a CLI library for Go that empowers applications.This application is a tool to generate the needed filesto quickly create a Cobra application.`, // Uncomment the following line if your bare application // has an action associated with it: Run: func(cmd *cobra.Command, args []string) { fmt.Println("Welcome to rootcmd") var mc Myconfig if err := viper.Unmarshal(&mc); err != nil { fmt.Println(err) } fmt.Println(mc) fmt.Println("I can print this ", viper.AllSettings()) },}
1 回答
斯蒂芬大帝
TA贡献1827条经验 获得超8个赞
您的问题归结为一个事实,即您的结构中的username
字段是否已导出。MyConfig
它需要大写才能“导出”Unmarshal
以将值解码到结构中。
type Myconfig struct { Username string `mapstructure:"username" }
您可以查看JSON 并处理未导出的字段,以更多地了解json
包需要它的原因。
- 1 回答
- 0 关注
- 211 浏览
添加回答
举报
0/150
提交
取消