douyigua5381 2018-11-19 10:59
浏览 139
已采纳

如何计算结构或JSON文档中的属性数量?

I'm making a PDF generator in Go and one of the sections of it will be a table. To create a table I need to state the width of the columns, and this will be done by getting the page width (minus margins) and dividing by the number of columns in the table

The columns in the table are defined in a struct like this:

type Person struct {
    Name    string `json:"Name"`
    Age     string `json:"Age"`
    Comment string `json:"Comment"`
}

And JSON is unmarshalled into it

I don't want to have to hardcode '3' as the column number into my code and want to know how I can programmatically count the properties either in from the JSON or the struct itself

I've spent a few days searching now, and all results focus on people having trouble getting the values, but I want the keys!

Thanks in advance

  • 写回答

2条回答 默认 最新

  • dony39517 2018-11-19 11:12
    关注
    reflect.TypeOf(Person{}).NumField()
    

    or

     len(structs.Map(Person{}))
    

    (you need to import "github.com/fatih/structs")

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题