Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

go

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

like image 327
ShapelyOwl Avatar asked Sep 20 '25 15:09

ShapelyOwl


1 Answers

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

or

 len(structs.Map(Person{}))

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

like image 96
Ehsan.Saradar Avatar answered Sep 22 '25 21:09

Ehsan.Saradar