我想解析这个
JSON(在config / synch.conf中):
{ "period" :"yy","exec_period" : { "start" : { "month" : 1,"week" : 2,"day" : 3,"hour" : 4,"minute" : 5 },"end" : { "month" : 6,"week" : 7,"day" : 8,"hour" : 9,"minute" : 10 } },"backup" : [ { "local_dir" : "directoryLo1","server_dir" : "directoryLo2","server_host" : "domaineName" },{ "local_dir" : "directoryLo1","server_dir" : "directorySe2","server_host" : "domaineName" } ],"incremental_save" : "1Y2M" }
有了这个程序:
package main import ( "encoding/json" "fmt" "io/IoUtil" ) func main() { content,err := IoUtil.ReadFile("config/synch.conf") if err == nil { type date struct{ month float64 week float64 day float64 hour float64 minute float64 } type period struct{ start date end date } type backupType []struct{ local_dir string server_dir string server_host string } type jason struct{ period string exec_period period backup backupType incremental_save string } var parsedMap jason err := json.Unmarshal(content,&parsedMap) if err!= nil { fmt.Println(err) } fmt.Println(parsedMap) } else { panic(err) } }
哪个不能按预期工作,因为输出是:
{ {{0 0 0 0 0} {0 0 0 0 0}} [] }
以下是play.golang.org上的相同示例
http://play.golang.org/p/XoMJIDIV59
我不知道这是否可以用go,但我想得到json.Unmarshal函数的值,该函数存储在map [string] interface {}(或允许的其他对象)中,我可以访问它,例如,分钟结束的值(10)是这样的:parsedMap [“exec_period”] [“end”] [“minute”],但我不理解golang的JSON and Go的“Generic JSON withinterface {}”部分.组织
您的代码很好,但json包只能用于导出的字段.
原文链接:https://www.f2er.com/go/186820.html如果您将每个字段名称的首字母大写,那么一切都会有效:
type date struct { Month float64 Week float64 Day float64 Hour float64 Minute float64 } type period struct { Start date End date } type backupType []struct { Local_dir string Server_dir string Server_host string } type jason struct { Period string Exec_period period Backup backupType Incremental_save string }
虽然可以编组到map [string] interface {}中,但如果数据具有设置结构(例如问题中的那个),则您的解决方案很可能更可取.使用接口{}将需要类型断言,并可能最终看起来凌乱.您的示例如下所示:
parsedMap["exec_period"].(map[string]interface{})["end"].(map[string]interface{})["minute"].(float64)