vjson is a Go package that helps to validate JSON objects in a declarative way.

vjson

vjson is a Go package that helps to validate JSON objects in a declarative way.

Getting Started

Installing

For installing vjson, use command below:

go get -u github.com/miladibra10/vjson

Concepts

There are two main concepts in vjson that are:

  • Schema
  • Field

Schema

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.

Field

A field contains characteristics of a specific field of a json object. multiple field types are supported by vjson. list of supported types are:

  • integer
  • float
  • string
  • boolean
  • array
  • object

How to create a Schema

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 in code

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.

Parse Schema

Schema could be parsed from a file or a string. These methods help to parse schema.

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.

Fields

Integer

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 min in validating json object.
  • Max(max int) forces the integer field to be lower than max in 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 field
  • type: type value for integer field must be integer
  • required: whether the field is required or not
  • min: minimum value of field
  • max: maximum value of field
  • positive: a boolean that describes that a field is positive or negative (true for positive and false for negative)
  • ranges: an array of ranges to be checked in field validation.

Example

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:

Code

vjson.Integer("foo").Required().Min(2).Max(10).Positive().Range(3,5).Range(6,8)

File

{
  "name": "foo",
  "type": "integer",
  "required": true,
  "min": 2,
  "max": 10,
  "positive": true,
  "ranges": [
    {
      "start": 3,
      "end": 5
    },
    {
      "start": 6,
      "end": 8
    }
  ]
}

Float

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 min in validating json object.
  • Max(max float64) forces the float field to be lower than max in 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 field
  • type: type value for float field must be float
  • required: whether the field is required or not
  • min: minimum value of field
  • max: maximum value of field
  • positive: a boolean that describes that a field is positive or negative (true for positive and false for negative)
  • ranges: an array of ranges to be checked in field validation.

Example

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:

Code

vjson.Float("foo").Required().Min(2.5).Max(10.5).Positive().Range(3,5).Range(6,8)

File

{
  "name": "foo",
  "type": "float",
  "required": true,
  "min": 2.5,
  "max": 10.5,
  "positive": true,
  "ranges": [
    {
      "start": 3,
      "end": 5
    },
    {
      "start": 6,
      "end": 8
    }
  ]
}

String

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 min in validating json object.
  • MaxLength(max int) forces the length of string field to be lower than max in validating json object.
  • Format(format string) gets a regex format 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 field
  • type: type value for string field must be string
  • required: whether the field is required or not
  • min_length: minimum length of string value of field
  • max_length: maximum length of string value of field
  • format: a regex format 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.

Example

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:

Code

vjson.String("foo").Required().MinLength(2).MaxLength(10).Choices("first", "second")

File

{
  "name": "foo",
  "type": "string",
  "required": true,
  "min_length": 2,
  "max_length": 10,
  "choices": [
    "first",
    "second"
  ]
}

Boolean

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

float field could be described by a json for schema parsing.

  • name: the name of the field
  • type: type value for string field must be boolean
  • required: whether the field is required or not
  • value: a boolean (same sa ShouldBe in code) that describes that the value of json field.

Example

a boolean field, named foo which is required, and always should be false, could be declared like this:

Code

vjson.Boolean("foo").Required().ShouldBe(false)

File

{
  "name": "foo",
  "type": "boolean",
  "required": true,
  "value": false
}

Array

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 min in validating json object.
  • MaxLength(max int) forces the length of array field to be lower than max in validating json object.

array field could be described by a json for schema parsing.

  • name: the name of the field
  • type: type value for array field must be array
  • required: whether the field is required or not
  • min_length: minimum length of array
  • max_length: maximum length of array
  • items: specifications of item fields. could be any field.

Example

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:

Code

vjson.Array("foo", vjson.Integer("item").Range(0,20)).Required().MinLength(2).MaxLength(10)

File

{
  "name": "foo",
  "type": "array",
  "required": true,
  "min_length": 2,
  "max_length": 10,
  "items": {
    "name": "item",
    "type": "integer",
    "ranges": [
      {
        "start": 0,
        "end": 20
      }
    ]
  }
}

Object

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 field
  • type: type value for object field must be object
  • required: whether the field is required or not
  • schema: schema of object value.

Example

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:

Code

vjson.Object("foo", vjson.NewSchema(
	vjson.String("name").Required(),
	vjson.String("last_name").Required(),
	)).Required()

File

{
  "name": "foo",
  "type": "object",
  "required": true,
  "schema": {
    "fields": [
      {
        "name": "name",
        "type": "string",
        "required": true
      },
      {
        "name": "last_name",
        "type": "string",
        "required": true
      }
    ]
  }
}

Validation

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 nil if the object is valid, and it will return an error if the input object is not valid.
  • ValidateString(input string): acts like ValidateBytes but its argument is string.

Example

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 := `
	{
		"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
	}
	
}
Similar Resources

A simple Go package to Query over JSON/YAML/XML/CSV Data

A simple Go package to Query over JSON/YAML/XML/CSV Data

A simple Go package to Query over JSON Data. It provides simple, elegant and fast ODM like API to access, query JSON document Installation Install the

Dec 27, 2022

a Go package to interact with arbitrary JSON

go-simplejson a Go package to interact with arbitrary JSON Importing import github.com/bitly/go-simplejson Documentation Visit the docs on Go package

Dec 29, 2022

jsonc is a Go package that converts the jsonc format to standard json.

jsonc jsonc is a Go package that converts the jsonc format to standard json. The jsonc format is like standard json but allows for comments and traili

Nov 22, 2022

JSONata in Go Package jsonata is a query and transformation language for JSON

JSONata in Go Package jsonata is a query and transformation language for JSON. It's a Go port of the JavaScript library JSONata.

Nov 8, 2022

A very rudimentary JSON compare package in GO

simple_json_compare A very rudimentary JSON compare package Sample code package main import ( "fmt" "github.com/CalypsoSys/simple_json_compare" )

Oct 20, 2021

A Go package to interact with arbitrary JSON

go-simplejson a Go package to interact with arbitrary JSON Importing import github.com/bitly/go-simplejson Documentation Visit the docs on Go package

Oct 20, 2021

This is an experimental package for working with JSON-LD documents in Go

JSON-LD šŸ”— Simple JSON-LD in Go This is an experimental package for working with JSON-LD documents in Go. Experimental, Pre-Alpha Quality Please do no

Jul 6, 2022

Abstract JSON for golang with JSONPath support

Abstract JSON Abstract JSON is a small golang package provides a parser for JSON with support of JSONPath, in case when you are not sure in its struct

Jan 5, 2023

Fast JSON parser and validator for Go. No custom structs, no code generation, no reflection

fastjson - fast JSON parser and validator for Go Features Fast. As usual, up to 15x faster than the standard encoding/json. See benchmarks. Parses arb

Jan 5, 2023
Comments
  • Allow for marshalling schema to JSON for storage

    Allow for marshalling schema to JSON for storage

    Having the ability to convert a properly formatted JSON string into a schema is great. But it'd work better if the reverse were also possible. Currently if you try to run a schema through json.Marshal, you get something similar to this:

    schema := vjson.NewSchema(
    	vjson.Float("i").Required(),
    	vjson.Array("children", vjson.String("item")),
    )
    
    byteStr, _ := json.Marshal(schema)
    
    println(string(byteStr)) // Output: [{},{}]
    

    Having complimentary functions to vjson.ReadFromBytes(), vjson.ReadFromString(), vjson.ReadFromFile() such as schema.WriteToString(...), schema.WriteToBytes(...), and schema.WriteToFile(...) would enable the proper backing up and restoring of these schemas.

  • Changed the field properties to be exported

    Changed the field properties to be exported

    As the title says, all the fields are now exported so you can use the json.Marshal function on them. This should fix #31 . As each one already had a "Required" method, most of the fields had to get an added "Field..." prefix to avoid conflicts while maintaining API compliance.

  • Questions about vjson

    Questions about vjson

    Iā€™m looking for a package to validate JSON and have a few questions before IĀ start trying your package.

    • Will it detect non ASCIIĀ characters in the JSONĀ data ?Ā 
    • Will it detect unmatched [] or {} ?
    • Will it detect missing or exceeding commas ?
    • Will it report the line number and character position in the line of the error ?
    • Are error human readable and more helpful than the errors provided by the standard library ?
  • Support for creating a schema from existing JSON or map[string]interface{}/struct

    Support for creating a schema from existing JSON or map[string]interface{}/struct

    As the title says, it'd be great to be able to create a schema on the fly from some existing JSON (or a map[string]interface{} or struct with JSON tags)

    Some examples of how that might work:

    // From struct
    type Data struct {
    	Name string `json:"name"`
    	Key string `json:"key"`
    }
    
    data := Data{
    	Name: "go",
    	Key: "myKey",
    }
    
    schema := vjson.NewSchema(
    	vjson.Struct(data)
    )
    
    // From a map
    data := map[string]interface{}{
    	"name": "go",
    	"key": "myKey",
    }
    
    schema := vjson.NewSchema(
    	vjson.Map(data)
    )
    
    // From a JSON string
    data := `{
    	"name": "go",
    	"key": "myKey"
    }`
    
    schema := vjson.NewSchema(
    	vjson.JSON(data)
    )
    

    All of which would be the equivalent in this case as:

    schema := vjson.NewSchema(
    	vjson.String("name").Required(),
    	vjson.String("key").Required(),
    )
    
Small utility to create JSON objects
Small utility to create JSON objects

gjo Small utility to create JSON objects. This was inspired by jpmens/jo. Support OS Mac Linux Windows Requirements Go 1.1.14~ Git Installtion Build $

Dec 8, 2022
Fluent API to make it easier to create Json objects.

Jsongo Fluent API to make it easier to create Json objects. Install go get github.com/ricardolonga/jsongo Usage To create this: { "name":"Ricar

Nov 7, 2022
simplest possible native GUI for inspecting JSON objects with jq
simplest possible native GUI for inspecting JSON objects with jq

./jqview The simplest possible native GUI for inspecting JSON objects with jq. Made with Qt and gojq. Usage ~> echo '[{"name": "Mises"}, {"name": "Hay

Oct 20, 2022
Example to validate performance using append or not in golang

benchtest-arr-go This code is a example to validate performance using append or not in golang result benchtests go test -benchmem -bench . goos: darwi

Jan 10, 2022
Package json implements encoding and decoding of JSON as defined in RFC 7159

Package json implements encoding and decoding of JSON as defined in RFC 7159. The mapping between JSON and Go values is described in the documentation for the Marshal and Unmarshal functions

Jun 26, 2022
Get JSON values quickly - JSON parser for Go
Get JSON values quickly - JSON parser for Go

get json values quickly GJSON is a Go package that provides a fast and simple way to get values from a json document. It has features such as one line

Dec 28, 2022
JSON diff library for Go based on RFC6902 (JSON Patch)

jsondiff jsondiff is a Go package for computing the diff between two JSON documents as a series of RFC6902 (JSON Patch) operations, which is particula

Dec 4, 2022
Fast JSON encoder/decoder compatible with encoding/json for Go
Fast JSON encoder/decoder compatible with encoding/json for Go

Fast JSON encoder/decoder compatible with encoding/json for Go

Jan 6, 2023
Json-go - CLI to convert JSON to go and vice versa
Json-go - CLI to convert JSON to go and vice versa

Json To Go Struct CLI Install Go version 1.17 go install github.com/samit22/js

Jul 29, 2022
A Go package for handling common HTTP JSON responses.

go-respond A Go package for handling common HTTP JSON responses. Installation go get github.com/nicklaw5/go-respond Usage The goal of go-respond is to

Sep 26, 2022