dongyue110702 2015-11-23 00:25
浏览 18
已采纳

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

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条回答 默认 最新

  • dousi2029 2015-11-23 00:52
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。