vjson is a Go package that helps to validate JSON objects in a declarative way.
For installing vjson, use command below:
go get -u github.com/miladibra10/vjson
There are two main concepts in vjson that are:
- Schema
- Field
A schema is the holder of JSON object specifications. It contains the way of validation of a JSON object. a schema consists of an array of fields.
A field contains characteristics of a specific field of a json object. multiple field types are supported by vjson.
list of supported types are:
integerfloatstringbooleanarrayobjectnullor
There are two ways to create a schema.
- Schema could be declared in code in a declarative manner.
- Schema could be parsed from a file or string.
Schema could be declared in code like this:
package main
import "github.com/miladibra10/vjson"
func main() {
schema := vjson.NewSchema(
vjson.String("name").Required(),
)
jsonString := `
{
"name": "James"
}
`
err := schema.ValidateString(jsonString)
if err != nil {
panic(err)
}
}schema object contains a string field, named name. This code validates jsonString.
Schema could be parsed from a file or a string. These methods help to parse schema.
- ReadFromString(input string): receives characteristics of a schema in a string format and returns a schema object and an error.
- ReadFromBytes(input []byte): receives characteristics of a schema in a byte array format and returns a schema object and an error.
- ReadFromFile(filePath string): receives file path of json file which contains characteristics of a schema, and returns a schema object and an error.
Format of schema for parsing should be a json like this:
{
"fields": [
...
]
}fields should contain field specifications.
This code parses a schema from string:
package main
import "github.com/miladibra10/vjson"
func main() {
schemaStr := `
{
"fields": [
{
"name": "name",
"type": "string"
"required": true
}
]
}
`
schema, err := vjson.ReadFromString(schemaStr)
if err != nil {
panic(err)
}
jsonString := `
{
"name": "James"
}
`
err = schema.ValidateString(jsonString)
if err != nil {
panic(err)
}
}schemaStr describes the schema and vjson.ReadFromString(schemaStr) parses the string and returns a schema object.
schema object contains a string field, named name. This code validates jsonString.
Note: You could Marshal your schema as a json object for backup usages with
json.Marshalfunction.
An integer field could be created in code like this:
vjson.Integer("foo")some validation characteristics could be added to an integer field with chaining some functions:
- Required() sets the field as a required field. validation will return an error if a required field is not present in json object.
- Min(min int) forces the integer field to be greater than
minin validating json object. - Max(max int) forces the integer field to be lower than
maxin validating json object. - Positive() checks if the value of field is positive.
- Negative() checks if the value of field is negative.
- Range(start, end int) adds a range for integer field. the value of json field should be within this range.
integer field could be described by a json for schema parsing.
name: the name of the fieldtype: type value for integer field must beintegerrequired: whether the field is required or notmin: minimum value of fieldmax: maximum value of fieldpositive: a boolean that describes that a field is positive or negative (truefor positive andfalsefor negative)ranges: an array of ranges to be checked in field validation.
an integer field, named foo which is required, minimum value should be 2, maximum value should be 10, should be positive and be within range [3,5] or [6,8] ,could be declared like this:
vjson.Integer("foo").Required().Min(2).Max(10).Positive().Range(3,5).Range(6,8){
"name": "foo",
"type": "integer",
"required": true,
"min": 2,
"max": 10,
"positive": true,
"ranges": [
{
"start": 3,
"end": 5
},
{
"start": 6,
"end": 8
}
]
}A float field could be created in code like this:
vjson.Float("foo")some validation characteristics could be added to a float field with chaining some functions:
- Required() sets the field as a required field. validation will return an error if a required field is not present in json object.
- Min(min float64) forces the float field to be greater than
minin validating json object. - Max(max float64) forces the float field to be lower than
maxin validating json object. - Positive() checks if the value of field is positive.
- Negative() checks if the value of field is negative.
- Range(start, end float64) adds a range for float field. the value of json field should be within this range.
float field could be described by a json for schema parsing.
name: the name of the fieldtype: type value for float field must befloatrequired: whether the field is required or notmin: minimum value of fieldmax: maximum value of fieldpositive: a boolean that describes that a field is positive or negative (truefor positive andfalsefor negative)ranges: an array of ranges to be checked in field validation.
a float field, named foo which is required, minimum value should be 2.5, maximum value should be 10.5, should be positive and be within range [3,5] or [6,8] ,could be declared like this:
vjson.Float("foo").Required().Min(2.5).Max(10.5).Positive().Range(3,5).Range(6,8){
"name": "foo",
"type": "float",
"required": true,
"min": 2.5,
"max": 10.5,
"positive": true,
"ranges": [
{
"start": 3,
"end": 5
},
{
"start": 6,
"end": 8
}
]
}A string field could be created in code like this:
vjson.String("foo")some validation characteristics could be added to a string field with chaining some functions:
- Required() sets the field as a required field. validation will return an error if a required field is not present in json object.
- MinLength(min int) forces the length of string field to be greater than
minin validating json object. - MaxLength(max int) forces the length of string field to be lower than
maxin validating json object. - Format(format string) gets a
regexformat and checks if value of json object matches the format. - Choices(choice ...string) checks if the value of string field is equal to one of choices.
float field could be described by a json for schema parsing.
name: the name of the fieldtype: type value for string field must bestringrequired: whether the field is required or notmin_length: minimum length of string value of fieldmax_length: maximum length of string value of fieldformat: aregexformat and checks if value of json object matches the format.choices: a list of strings that value of field should be equal to one of them.
a string field, named foo which is required, minimum length value should be 2, maximum length value should be 10, should be Equal to one of these values: first, second could be declared like this:
vjson.String("foo").Required().MinLength(2).MaxLength(10).Choices("first", "second"){
"name": "foo",
"type": "string",
"required": true,
"min_length": 2,
"max_length": 10,
"choices": [
"first",
"second"
]
}A boolean field could be created in code like this:
vjson.Boolean("foo")some validation characteristics could be added to a boolean field with chaining some functions:
- Required() sets the field as a required field. validation will return an error if a required field is not present in json object.
- ShouldBe(value bool) forces the value of field be equal to
value
boolean field could be described by a json for schema parsing.
name: the name of the fieldtype: type value for boolean field must bebooleanrequired: whether the field is required or notvalue: a boolean (same saShouldBein code) that describes that the value of json field.
a boolean field, named foo which is required, and always should be false, could be declared like this:
vjson.Boolean("foo").Required().ShouldBe(false){
"name": "foo",
"type": "boolean",
"required": true,
"value": false
}An array field could be created in code like this:
vjson.Array("foo", vjson.String("item"))the first argument is the name of array field, and the second one is the field characteristics of each item of array.
some validation characteristics could be added to an array field with chaining some functions:
- Required() sets the field as a required field. validation will return an error if a required field is not present in json object.
- MinLength(min int) forces the length of array field to be greater than
minin validating json object. - MaxLength(max int) forces the length of array field to be lower than
maxin validating json object.
array field could be described by a json for schema parsing.
name: the name of the fieldtype: type value for array field must bearrayrequired: whether the field is required or notmin_length: minimum length of arraymax_length: maximum length of arrayitems: specifications of item fields. could be any field.
an array field, named foo with integer items between [0,20] range, which is required, and its length should be at least 2 and at last 10, could be declared like this:
vjson.Array("foo", vjson.Integer("item").Range(0,20)).Required().MinLength(2).MaxLength(10){
"name": "foo",
"type": "array",
"required": true,
"min_length": 2,
"max_length": 10,
"items": {
"name": "item",
"type": "integer",
"ranges": [
{
"start": 0,
"end": 20
}
]
}
}An object field could be created in code like this:
vjson.Object("foo", vjson.NewSchema(
/// Fields
))the first argument is the name of object field, and the second one is the schema of object value. this feature helps validation of nested json objects
some validation characteristics could be added to an array field with chaining some functions:
- Required() sets the field as a required field. validation will return an error if a required field is not present in json object.
object field could be described by a json for schema parsing.
name: the name of the fieldtype: type value for object field must beobjectrequired: whether the field is required or notschema: schema of object value.
a required object field, named foo which its valid value is an object with name and last_name required strings, could be declared like this:
vjson.Object("foo", vjson.NewSchema(
vjson.String("name").Required(),
vjson.String("last_name").Required(),
)).Required(){
"name": "foo",
"type": "object",
"required": true,
"schema": {
"fields": [
{
"name": "name",
"type": "string",
"required": true
},
{
"name": "last_name",
"type": "string",
"required": true
}
]
}
}A null field (a field that its value should be null!) could be created in code like this:
vjson.Null("foo")null field could be described by a json for schema parsing.
name: the name of the fieldtype: type value for null field must benull
a null field, named foo, could be declared like this:
vjson.Null("foo"){
"name": "foo",
"type": "null"
}An Or field could be created in code like this:
vjson.Or("foo", vjson.String("bar"), vjson.Boolean("baz"))The Or field validates if a value matches at least one of the provided field types.
You can provide the field types directly in the constructor, or add them later using the WithFields method.
some validation characteristics could be added to an Or field with chaining some functions:
- Required() sets the field as a required field. validation will return an error if a required field is not present in json object.
- WithFields(fields ...Field) replaces field types to check. The value will be valid if it matches at least one of these field types.
Or field could be described by a json for schema parsing.
name: the name of the fieldtype: type value for Or field must beorrequired: whether the field is required or not
an Or field, named foo which is required, and accepts either a string or a boolean, could be declared like this:
vjson.Or("foo", vjson.String("bar"), vjson.Boolean("baz")).Required()Alternatively, you can add fields using the WithFields method:
vjson.Or("foo").Required().WithFields(vjson.String("bar"), vjson.Boolean("baz")){
"name": "foo",
"type": "or",
"required": true,
"fields": [
{
"name": "foo",
"type": "null"
},
{
"name": "foo",
"type": "string",
"required": true
}
]
}After creating a schema, you can validate your json objects with these methods:
- ValidateBytes(input []byte): receives a byte array as a json input and validates it. this method returns an error. it would be
nilif the object is valid, and it will return an error if the input object is not valid. - ValidateString(input string): acts like
ValidateBytesbut its argument is string.
This code validates an object that should have name and age fields.
package main
import "github.com/miladibra10/vjson"
func main() {
schema := vjson.NewSchema(
vjson.String("name").Required(),
vjson.Integer("age").Positive(),
)
jsonString := `
{
"required": true,
"value": false"name": "James"
}
`
err := schema.ValidateString(jsonString)
if err != nil {
panic(err) // Will not panic
}
jsonString = `
{
"name": "James",
"age": 10
}
`
err = schema.ValidateString(jsonString)
if err != nil {
panic(err) // Will not panic
}
jsonString = `
{
"age": 10
}
`
err = schema.ValidateString(jsonString)
if err != nil {
panic(err) // Will panic because name field is missing in jsonString
}
}Results of benchmarking validation functions highly depends on types and number of fields.
two simple benchmarks (exists in schema_test.go file) with using all features of vjson gives this result:
goos: linux
goarch: amd64
pkg: github.com/miladibra10/vjson
BenchmarkSchema_ValidateString-8 416664 2792 ns/op
BenchmarkSchema_ValidateBytes-8 431734 2858 ns/op
PASS
ok github.com/miladibra10/vjson 2.461s