JSON decoder does not work as expected

Please consider the following code:

package main

import (
	"fmt"
	"encoding/json"
	"bytes"
)

func main() {
	j := []byte("{\"bandwidth\":5120}")
	type M struct {
	    rate float64 `json:"bandwidth"`
	}
	r := M{}
	decoder := json.NewDecoder(bytes.NewReader(j))
	err := decoder.Decode(&r)
	fmt.Printf("%+v %+v", r, err)
}

It returns {rate:0} <nil>, what is wrong with it?

The JSON decoder does only work for public fields. You need to make it Rate. Also Iā€™m not sure if it works with function local types at all or if they need to be at the package level.

2 Likes

Function local types work just fine. I use them when I need a struct just for the function.

1 Like

Just change the struct to

type M struct {
	Bandwidth float64 `json:"bandwidth"`
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.