-2

I am trying to return a json with a list in each property but I am always obtaining the lists as empty lists. It seems that I have a mistake inside a structure but I cannot found it.

I have two structs:

type CalendarDay struct {
    day     int    `json:"day"`
    weekday string `json:"weekday"`
}

type CalendarYear struct {
    January   []CalendarDay `json:"january"`
    February  []CalendarDay `json:"february"`
    March     []CalendarDay `json:"march"`
    April     []CalendarDay `json:"april"`
    May       []CalendarDay `json:"may"`
    June      []CalendarDay `json:"june"`
    July      []CalendarDay `json:"july"`
    August    []CalendarDay `json:"august"`
    September []CalendarDay `json:"september"`
    October   []CalendarDay `json:"october"`
    November  []CalendarDay `json:"november"`
    December  []CalendarDay `json:"december"`
}

I'm trying to return a json as:

{
    "january": [{1 Thursday}, ...]
    ...
}

but I obatain:

{
    "january": [{}, {}, {} ...]
    ...
}

My API is:

func Calendar(w http.ResponseWriter, r *http.Request) {
    fmt.Println("GET /")
    year := getYear(2015)
    json.NewEncoder(w).Encode(year)
}

func getMonthDays(month time.Month, year int) []CalendarDay {
    cdays := []CalendarDay{}
    for i := 1; i <= daysIn(month, year); i++ {
        date := time.Date(year, month, i, 0, 0, 0, 0, time.UTC)
        weekday := date.Weekday()
        cday := CalendarDay{
            day:     date.Day(),
            weekday: weekday.String()}
        cdays = append(cdays, cday)
    }
    return cdays
}

func getYear(year int) CalendarYear {
    yearCal := CalendarYear{
        January:   getMonthDays(time.January, year),
        February:  getMonthDays(time.February, year),
        March:     getMonthDays(time.March, year),
        April:     getMonthDays(time.April, year),
        May:       getMonthDays(time.May, year),
        June:      getMonthDays(time.June, year),
        July:      getMonthDays(time.July, year),
        August:    getMonthDays(time.August, year),
        September: getMonthDays(time.September, year),
        October:   getMonthDays(time.October, year),
        November:  getMonthDays(time.November, year),
        December:  getMonthDays(time.December, year)}
    return yearCal
}

What am I doing wrong?

Emil
  • 85
  • 1
  • 6

1 Answers1

2

Export the fields in CalendarDay by starting the name with an uppercase character.

type CalendarDay struct {
    Day     int    `json:"day"`
    Weekday string `json:"weekday"`
}

The encoding/json package and similar packages ignore unexported fields.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242