-4
type ApiResponse struct {
    Success bool     `json:"success"`
    Errors  []string `json:"errors"`
}

type NewSessionResponse struct {
    ApiResponse     `json:"apiResponse"`
    authToken   string `json:"authToken"`
}

In my handler I am doing this:

resp := NewSessionResponse{ApiResponse{true, []string{}}, "auth123"}

json.NewEncoder(w).Encode(resp)

The response I am seeing is this:

{
    apiResponse: {
        success: true,
        errors: [ ]
    }
}

Why isn't my authToken property in the JSON result?

Abu Hanifa
  • 2,857
  • 2
  • 22
  • 38
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

1 Answers1

3

authToken filed is an unexported field. Json library does not have the power to view fields using reflect unless they are exported. A package can only view the unexported fields of types within its own package.

You can export the filed to get this working

type NewSessionResponse struct {
    ApiResponse     `json:"apiResponse"`
    AuthToken   string `json:"authToken"`
}

FYI: Exported identifiers https://golang.org/ref/spec#Exported_identifiers

Anuruddha
  • 3,187
  • 5
  • 31
  • 47