如何以 JSON 格式显示 Golang 中地图的所有数据?

huangapple go评论81阅读模式
英文:

How to display all data from a map in json format - Golang?

问题

我正在使用golang创建一个API,它将以JSON格式简单地显示来自map的所有数据。
端点:/keys

type UserController struct{}

// NewUserController函数
func NewUserController() *UserController {
    return &UserController{}
}

// Data结构体
type Data struct {
    Datakey   int    `json:"key"`
    Datavalue string `json:"value"`
}

var datamap = make(map[int]string)

func (uc UserController) getallkeys(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
    type Users []Data
    var uj Users
    for k, v := range datamap {
        uj = append(uj, Data{
            Datakey:   k,
            Datavalue: v,
        })
    }

    result, _ := json.Marshal(uj)
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(200)
    fmt.Fprintf(w, "%s", result)
}

例如:
响应应该类似于

[
  {
    "key": somekey,
    "value": "somevalue"
  },
  {
    "key": somekey,
    "value": "somevalue"
  }
]

我不清楚如何实现这个。上面的代码只显示了map中的最后一个数据。这是不正确的,但我不确定如何继续。如果有人能帮助我,那就太好了。

谢谢。

英文:

I am creating a API in golang which will simply display all data from a map in json format.
endpoint: /keys

type UserController struct{}
    
// NewUserController function
func NewUserController() *UserController {
    return &UserController{}
}
        
// Data struct
type Data struct {
    Datakey   int    `json:"key"`
    Datavalue string `json:"value"`
}
        
var datamap = make(map[int]string)

func (uc UserController) getallkeys(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
    type Users []Data
    var uj Users
    for k, v := range datamap {
        uj = Users{
    	    Data{
    		    Datakey:   k,
    			Datavalue: v,
    		},
    	}
    }
    
    result, _ := json.Marshal(uj)
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(200)
    fmt.Fprintf(w, "%s", result)
}

For eg:
The response should be something like

[
  {
    "key":somekey,
    "value":"somevalue"
  },
  {
    "key":somekey,
    "value":"somevalue"
  }
]

I am not clear how to implement this. The above code is displaying just the last data from the map. This is incorrect but I am not sure how to proceed. It would be great if someone could help me with this.

Thanks.

答案1

得分: 1

至少有两个不同的问题。

首先,一个 JSON Map 不能有一个 int 键。这是 JSON 规范的一部分。要么将其更改为字符串,要么您将不得不为该映射实现 MarshalJSON 和 UnmarshalJSON 接口,即为类型

    type MyMap map[int]string

Google golang UnmarshalJSON time.Duration 以获取一些基本示例。还要注意映射和您特定的键类型。

其次,对于切片类型

    type Users []Data

添加元素需要使用 append

    uj := make(Users,0)
    for k, v := range datamap {
        d := Data{k,v}
        uj = append(uj, d) 
    }

当然,将切片编组为一个无键的 JSON Map -- 这可能不是您想要的结果。

英文:

At least two different problems.

First, a JSON Map cannot have an `int' key. That is part of the JSON spec. Either change it to a string or you will have to implement the MarshalJSON and UnmarshalJSON interfaces for the map, i.e, for the type

    type MyMap map[int]string

Google golang UnmarshalJSON time.Duration for a number of basic examples. Also, against map and your specific key type.

Second, for a slice type

    type Users []Data

adding elements requires append

    uj := make(Users,0)
    for k, v := range datamap {
        d := Data{k,v}
        uj = append(uj, d) 
    }

Of course, marshaling a slice produces a keyless JSON map -- likely not what you want.

huangapple
  • 本文由 发表于 2015年11月23日 08:25:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/33861992.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定