Format Gorm struct to proper JSON

Hello!

I’m trying to set up an API using Gorm, it works smootly, however, my JSON format is not correct.

For instance, a GET request returns it with bad formatted.

[
  {
    "ID": 1,
    "CreatedAt": "2017-03-16T11:37:16.14044-05:00",
    "UpdatedAt": "2017-03-16T11:37:16.14044-05:00",
    "DeletedAt": null,
    "name": "Lions",
    "description": "This is the lions cohort"
  }
]

It should be

[
  {
    "id": 1,
    "created_at": "2017-03-16T11:37:16.14044-05:00",
    "updated_at": "2017-03-16T11:37:16.14044-05:00",
    "deleted_at": null,
    "name": "Lions",
    "description": "This is the lions cohort"
  }
]

And this is my struct:

package models

import "github.com/jinzhu/gorm"

// Cohort represents any given cohort in the site
type Cohort struct {
	gorm.Model
	Name        string `gorm:"type:varchar(40); unique_index; not null" json:"name"`
	Description string `gorm:"type:varchar(255); not null" json:"description"`
	Users       []User `json:"users,omitempty"`
}

Is this the correct approach?

package models

import "time"

// Cohort represents any given cohort in the site
type Cohort struct {
	ID          uint       `gorm:"primary_key" json:"id"`
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
	DeletedAt   *time.Time `json:"deleted_at"`
	Name        string     `gorm:"type:varchar(40); unique_index; not null" json:"name"`
	Description string     `gorm:"type:varchar(255); not null" json:"description"`
	Users       []User     `json:"users,omitempty"`
}

Thank you so much!

1 Like