Json Unmarshaling in Golang

Issue

I want to unmarshal the followng json in golang. I am not able to access the inner data .
What is the best way to do it?

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

I use

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("%+v\n", r)

but i dont see the values inside the struct.
Result: map[1:{enabled:false pct:0} 2:{enabled:false pct:0} 3:{enabled:false pct:0} 4:{enabled:false pct:0}]

Solution

For Marshaling and Unmarshaling, you should define struct field as exported field, also the destination should be map of regs.
Also the bool type is not valid for the Enabled and you should change it to 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)
}

The output will be:

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

Answered By – S4eed3sm

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.