亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang中的Json Unmarshaling

Golang中的Json Unmarshaling

Go
子衿沉夜 2022-11-08 16:30:55
我想在golang中解組followng 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]regsif err := json.Unmarshal([]byte(jStr), &r); err != nil {    log.Fatal(err)}fmt.Printf("%+v\n", r)但我沒有看到結構內的值。結果:map[1:{enabled:false pct:0} 2:{enabled:false pct:0} 3:{enabled:false pct:0} 4:{enabled:false pct:0}]
查看完整描述

1 回答

?
搖曳的薔薇

TA貢獻1793條經驗 獲得超6個贊

對于 Marshaling 和 Unmarshaling,您應該將 struct 字段定義為導出字段,并且目標應該是 regs 的映射。此外 bool 類型對 the 無效,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}]


查看完整回答
反對 回復 2022-11-08
  • 1 回答
  • 0 關注
  • 117 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號