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 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义