首页 > 解决方案 > 如何使用包含 []array 制作 []array & map

问题描述

如何制作类似的地图"Data":[{"3":{...}},{"4":{...}}]

控制器

jsons := make(map[string]interface{})
listUsers := identity.ListUsers()
users := make(map[int]interface{})

for k, j := range listUsers {
        if j.Description != "" {
            users[k] = j
    }
}

jsons["Data"] = users
u.Data["json"] = jsons
u.ServeJSON()

JSON

 "Data": {
    "3": {
        "default_project_id": "",
        "description": "description",
        "domain_id": "default",
        "enabled": true
    },
    "5": {
        "default_project_id": "9e266e1a750e45f8862e83341a5d0970",
        "description": "description",
        "domain_id": "default",
        "enabled": true
    }
}

请帮我解决这个错误

listUsers []users.User 用户映射[int]interface{}

当我得到答案时,我只需要添加更多细节。

标签: jsonapigocontrollerbeego

解决方案


我认为您应该创建新类型:

type AutoGenerated struct {
DefaultProjectID string `json:"default_project_id"`
Description      string `json:"description"`
DomainID         string `json:"domain_id"`
Enabled          bool   `json:"enabled"`

}

类型 MyType map[int]AutoGenerated

我认为创建一片地图不是一个好主意,但可以:

type SliceMap []MyType

要从 JSON 生成新的 go-types,您可以使用:https ://mholt.github.io/json-to-go/


推荐阅读