doushou3814 2017-08-03 12:03 采纳率: 100%
浏览 54
已采纳

如何在json中显示映射键和结构的值

I've this piece of code.

package main

import (
    "github.com/gin-gonic/gin"
    _ "github.com/go-sql-driver/mysql"
)

func divisionsHandler(c *gin.Context) {
    divisions := getDivisionRows()
    json := make(map[int]string)
    for divisions.Next() {
        var d Division
        err := divisions.Scan(&d.id, &d.name)
        json[d.id] = d.name
        if err != nil {
            panic(err.Error())
        }
    }
    c.JSON(200, json)
}

The result is

{
    1: "games",
    2: "technology",
    3: "tekk",
    4: "home entertainment",
    5: "toys & stationery"
}

I am trying to convert that json in something like

{
    [{
        "id": 1,
        "name": "games"
    },
    ...
    ]
}

but how?

  • 写回答

1条回答 默认 最新

  • doulachan8217 2017-08-03 12:06
    关注

    So you want a json array instead of a json object?

    Instead of loading a map[int]string, why not simply make a []Division?

    list := []Division{}
    for divisions.Next() {
        var d Division
        err := divisions.Scan(&d.id, &d.name)
        list = append(list, d)
        if err != nil {
            panic(err.Error())
        }
    }
    

    You'll need to change the field names to ID and Name so that the json package can serialize them, but you should end up with somthing more like:

    [
      {"ID":1,"Name":"Games},
      ...
    ]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?