Go map[int]struct JSON Marshal

col*_*ass 1 json struct marshalling go

尝试在 go 中将 map[int] 解析为用户定义的结构:

这是数据模式。

type Recommendation struct {
    Book  int     `json:"book"`
    Score float64 `json:"score"`
}
Run Code Online (Sandbox Code Playgroud)

这是 json 编组:

ureco := make(map[int]data.Recommendation)
ureco, _ = reco.UserRunner()

json, _ := json.Marshal(ureco)
fmt.Println(json)
Run Code Online (Sandbox Code Playgroud)

其中 reco.UserRunner() 返回适当的结构类型。

这将打印一个空的 json 对象:

[]
Run Code Online (Sandbox Code Playgroud)

更新:

错误信息:

json: unsupported type: map[int]data.Recommendation
Run Code Online (Sandbox Code Playgroud)

那么我如何 json 结构映射?还是有替代方法?

det*_*000 5

如果你只需要编组它,你可以遍历你的地图并将它变成一个切片。

slc := make([]data.Recommendation)
for _, val := range ureco {     
    slc = append(out, val)
}
json, _ := json.Marshal(slc)
Run Code Online (Sandbox Code Playgroud)

你可以map[int]string在这里看到一个简单的例子:http : //play.golang.org/