Json Unmarshaling in Golang



我想在golang中解组以下json。我无法访问内部数据。最好的方法是什么?

{
"1": {
"enabled": 1,
"pct": 0.5
},
"2": {
"enabled": 1,
"pct": 0.6
},
"3": {
"enabled": 1,
"pct": 0.2
},
"4": {
"enabled": 1,
"pct": 0.1
}
}

我使用

type regs struct {
enabled bool    `json:"enabled,omitempty"`
pct     float64 `json:"pct,omitempty"`
}
var r map[string]regs
if err := json.Unmarshal([]byte(jStr), &r); err != nil {
log.Fatal(err)
}
fmt.Printf("%+vn", r)

但是我看不到结构中的值。结果:map[1:{enabled:false pct:0} 2:{enabled:false pct:0} 3:{enabled:false pct:0} 4:{enabled:false pct:0}]

对于封送和取消封送,您应该将结构字段定义为导出字段,并且目的地应该是regs的映射。此外,bool类型对Enabled无效,您应该将其更改为int

type regs struct {
Enabled int     `json:"enabled,omitempty"`
Pct     float64 `json:"pct,omitempty"`
}
func main() {
a := `{
"1": {
"enabled": 1,
"pct": 0.5
},
"2": {
"enabled": 1,
"pct": 0.6
},
"3": {
"enabled": 1,
"pct": 0.2
},
"4": {
"enabled": 1,
"pct": 0.1
}
}`
dest := make(map[string]regs)
json.Unmarshal([]byte(a), &dest)
fmt.Println(dest)
}

输出为:

map[1:{1 0.5} 2:{1 0.6} 3:{1 0.2} 4:{1 0.1}]

最新更新