如何计算结构或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
我正在Go中制作PDF生成器,它的其中一部分将是一张表。 要创建表,我需要声明列的宽度,这将通过获取页面宽度(减去边距)并除以表中的列数来完成。 p>
表中的列在这样的结构中定义: p>
type Person struct {
Name string`json:“ Name”`
Age string`json:“ Age “`
评论字符串`json:” Comment“`
}
code> pre>
并且将JSON解组到其中 p>
我不想将“ 3”作为列号硬编码到我的代码中,也不想知道如何以编程方式从JSON或结构本身中计算属性 p>
我现在花了几天时间,所有结果都集中在难以获取值的人上,但是我想要键! p>
先谢谢了 p>
DIV>
reflect.TypeOf(Person{}).NumField()
or
len(structs.Map(Person{}))
(you need to import "github.com/fatih/structs")
The Object.getOwnPropertyNames(object)
will return an array of property name for the given object