Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate JSON input

I'm using Beego framework to build a web application in Go. I have to validate the incoming JSON in an API request.

I can unmarshal the JSON into a struct which works fine, but I want to validate the data as well. For example, if the type doesn't match with the type in struct json.Unmarshal will reutrn an error on the first occurence. I want to validate and get all the errors at once for JSON.

I've tried https://github.com/thedevsaddam/govalidator but the package needs a reference to request object which is not available in the controller of Beego. There are other validators which can validate a struct but i want the json validation as well.

EDIT:

A reference to the request object in beego can be found from the controller's context object as:

func (this *MainController) Post() {
    fmt.Println(this.Ctx.Request)
}

But the problem remains same with json unmarshal. If there's any slight mismatch in the type, json.unmarshal will immediately panic. I want to be able to validate the type as well.

like image 309
anshuraj Avatar asked May 30 '19 12:05

anshuraj


1 Answers

Since Golang v1.9 json.Valid([]byte) has been a valid method available from the "encoding/json" package.

Reference: https://golang.org/pkg/encoding/json/#Valid

like image 184
danielkalen Avatar answered Oct 14 '22 03:10

danielkalen