jsonrestapigostruct

How to Parse JSON Request Body with an Array to Create a Relationship Between Structs


I'm using Go (Golang)/Chi to create a REST API.

This is the structure of the JSON payload from the request body:

{
  "name": "John Smith",
  "bornDate": "2020-10-05",
  "books": [
     {
       "title": "Book 1 Title",
       "publishYear": "1989"
     },
     {
       "title": "Book 2 Title",
       "publishYear": "1999"
     }
   ]
}

And here are the Structs I'm attempting to impart onto this request:

type AuthorRequest struct{
    Name string `json: "name"`
    BornDate string `json: "bornDate"`
    Books []BookRequest `json: "books"`
}

type BookRequest struct{
    Title string `json: "title"`
    PublishYear string `json: "publishYear"`
}

And I'm attempting to save AuthorRequest and BookRequest down as Author Struct and Book Struct.

type Author struct{
    Name string
    BornDate time.Time
    Books []Book
}

type Book struct{
    Title string
    PublishYear int32
}

And this is my handler function for this POST request:

func CreateAuthorAndBooks(w http.ResponseWriter, r *http.Request) {
   // Assume that AuthorRequest is in an api package
   var authorPayload api.AuthorRequest
   decoder := json.NewDecoder(r.Body)
   err := decoder.Decode(&authorPayload)

   if err != nil{
     // Logging an error here on missing fields
   }

   var successMessage string = fmt.Sprintf("%v's has %v books: %v", authorPayload.Name, len(authorPayload.Books), authorPayload.Books)
   var response map[string]string = map[string]string{"success": successMessage}
   w.Header().Set("Content-Type", "application/json")
   
   var err = json.NewEncoder(w).Encode(response)
   if err != nil{
     // Logging an internal server error
   }
  // Logic to create Author and its related Book Structs...
}

But for some reason, when I send the above JSON request body and receive a response, there are 0 books and there is an empty slice [] when referencing books.

How do I properly parse and access an array within a JSON request body for a POST request in Go/Chi?


Solution

  • The space that you have included after the json struct tag that might be causing problem here removing that space should resolve the problem.

    type AuthorRequest struct{
        Name      string        `json:"name"`
        BornDate  string        `json:"bornDate"`
        Books     []BookRequest `json:"books"`
    }
    
    type BookRequest struct{
        Title       string `json:"title"`
        PublishYear string `json:"publishYear"`
    }