Unable to json validate array of Structs

Hi All,

I am trying to validate the json array. First I unmarshall it to the array of Structs.

package main

import (


var validate *validator.Validate

type Event struct {
	Name string `json:"name" validate:"required"`
	Type string `json:"type" validate:"required"`

func main() {
	payload := `[{"name":"bitrate_adjusted","type":"quality"}, {"name":"play","type":"playback"}]`

	validate := validator.New()

	var plStruct []Event
	fmt.Printf("PayLoad: %s\n\n", payload)
	if err := json.Unmarshal([]byte(payload), &plStruct); err != nil {
		fmt.Printf("PayLoad Struct: %s", plStruct)
		fmt.Printf("Error in payload: %s\n", err)
	fmt.Printf("PayLoad Struct: %s\n", plStruct)
	if err := validate.Struct(plStruct); err != nil {
		fmt.Printf("Error Validating Payload: %s\n", err)
	} else {
		fmt.Printf("no issues...")


PayLoad: [{"name":"bitrate_adjusted","type":"quality"}, {"name":"play","type":"playback"}]

PayLoad Struct: [{bitrate_adjusted quality} {play playback}]
Error Validating Payload: validator: (nil []main.Event)

Is there any way to validate the array of events directly without using the loop.

Hello there!


validate struct only validates structs. In the part of your code you are trying to validate slice not the struct, you need to loop on all of them and call that or you can use the deep dive required with a struct containing slices.

See the usage of Addresses of User here.

Personally, I am against using struct tags of struct to do a validation since this package uses reflection at runtime.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.