-1

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}]

Magic Wand
  • 25
  • 7
  • Hi MagicWand, you need to [export the fields](https://go.dev/ref/spec#Exported_identifiers) to be able to unmarshal the json. Fields that begin with a lowercase letter, including an underscore, are considered unexported which means they are not accessible outside of the package in which they were declared, and because of that the `encoding/json` package has no access to the fields that you declared in your package. – mkopriva Feb 17 '22 at 18:56

1 Answers1

1

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}]
S4eed3sm
  • 1,398
  • 5
  • 20