How can I count the number of properties in a struct or JSON document?

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

Upvotes: 4

Views: 7291

Answers (1)

Ehsan.Saradar
Ehsan.Saradar

Reputation: 704

reflect.TypeOf(Person{}).NumField()

or

 len(structs.Map(Person{}))

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

Upvotes: 12

Related Questions