Skip to main content

No project description provided

Project description

JSON Validator

License: GPL v3 GitHub issues GitHub stars GitHub forks

JSON Validator is a Python library designed to enhance the validation of JSON documents. It provides a simple yet powerful set of features for schema-based validation, offering flexibility and precision in handling JSON data.

Outline

Overview

JSON Validator is a feature-rich Python library designed to elevate the validation of JSON documents by offering an extensive schema-based validation system. It empowers developers to define custom schemas, providing fine-grained control over the structure, data types, and constraints of their JSON data.

Key Features

1. Schema Definition

Define a schema for your JSON documents, specifying keys, data types, and constraints. The schema acts as a blueprint for validation.

2. Flexible Data Type Validation

Control the data types of each key in your JSON document. Enforce strict typing or allow flexibility based on your requirements.

3. Key Presence Validation

Detect and handle invalid keys in your JSON document that are not defined in the schema, ensuring data integrity.

4. Required and Optional Fields

Designate which fields are required and which are optional, guiding users in creating valid JSON documents.

5. Child Value Bypass

Allow bypassing the validation of child values, providing flexibility when certain sections of the JSON document don't require strict validation.

6. Value Bindings

Support value bindings to establish relationships between different parts of the JSON document, enhancing the expressiveness of your schemas.

7. Regular Expression Bindings

Support regular expression bindings for precise validation of values..

8. String Value Constraints

Control the minimum and maximum length of string values, applying constraints to ensure data meets specific length requirements.

9. Numeric Value Constraints

Define minimum and maximum values for integer and float types, allowing precise control over the numeric range of your data.

10. Case Constraints

Apply case constraints to string types, specifying whether they should be in lower, upper, or mixed case.

11. Spacing in String Values

Optionally allow spacing in string data types, enhancing readability in scenarios where formatted text is essential.

12. Custom Extension Library

Extend the functionality of the library by creating custom extensions, tailoring the validation process to your unique needs.

Installation

install pip jsvl

Command line guide

List of available commands

Command Definition
-s or --schema Provide a schema json, file or a directory path for validating the documents.
-d or --doc Provide a document json, file or a directory path for validation.
Note: if the schema source is a directory then provided schema should be in a directory and should have the same name with _schema postfix.
-csfp or --change-schema-file-postfix This argument will be used to change the schema file postfix name.
--disable-tags Pass this flag to disable the output tags from logs.
--plain-output Pass this flag to remove the formatting from logs.
--disable-logs Pass this flag to disable all the logs.
--show-validation-source Pass this flag to show the validation class name with logs.
--tight-space Pass this flag to disable the allow_space globally.
-ml or --min-length Set the minimum length globally, default is 0.
-xl or --max-length Set the maximum length globally, default is None.
-mv or --min-value Set the minimum value globally, default is 0.
-xv or --max-value Set the maximum value globally, default is None.
-c or --case Set the text constraints globally, default is None. set Available Keywords
-v or --version Check version.
-h or --help For help.

How to use

Command line

Validate a single json document.

~$ python jsvl -s /path/to/schema.json -i /path/to/document.json

Validate multiple documents with a single schema.

~$ python jsvl -s /path/to/schema.json -i /path/to/documents/

Validate multiple documents with multiple schema.

~$ python jsvl -s /path/to/schema/ -i /path/to/documents/

Validate single or multiple documents with remote schema.

~$ python jsvl -s http://www.yourdomain.com/schema.json -i /path/to/document.json

Disable informative tags from the output.

~$ python jsvl -s path/to/schema.json -i /path/to/document.json --disable-tags

Remove formatting from the output.

~$ python jsvl -s path/to/schema.json -i /path/to/document.json --plain-output

Use in Project:

Import validator function from jsvl.core module and validate the document with multiple options.

from jsvl.core import validator

# schema json
schema = "path/to/schema.json" or "path/to/all_schema_dir/" or {}

# document json
document = "path/to/document.json" or "path/to/all_documents_dir/" or {} or []

# perform validation
result = validator.validate(schema, document)

Control Configs:

from jsvl.core import validator
import jsvl.config as cfg
from jsvl.utils.util import reserved_key

# change schema file postfix default is _schema
cfg.configs[cfg.schema_file_postfix] = "_schema"

# disable the output tags from logs
cfg.configs[cfg.enable_output_tags] = False

# remove the formatting from logs
cfg.configs[cfg.formatted_output] = False

# disable all the logs
cfg.configs[cfg.enable_output_logs] = True

# show the validation class name with logs
cfg.configs[cfg.enable_validation_source] = True

# disable the allow_space globally
cfg.configs[cfg.allow_space] = True

# set the minimum length globally, default is 0.
cfg.configs[cfg.min_length] = 0

# set the maximum length globally, default is None.
cfg.configs[cfg.max_length] = 1000

# set the minimum value globally, default is 0.
cfg.configs[cfg.min_value] = 0

# set the maximum value globally, default is None.
cfg.configs[cfg.max_value] = 1000

# set the text constraints globally, default is None.
cfg.configs[cfg.case] = reserved_key.upper

Register Custom Validation Filters:

You can register two types of validation filter.

  1. Schema Validation
from jsvl.validations import schema_validation_set, SchemaValidation

# creating custom filter class for schema validation
class CustomSchemaValidation(SchemaValidation):

    def validate(self, key, schema, path):
        print(key)

# register filter in schema validation set
schema_validation_set.add(CustomCheckForSchemaValidation())
  1. Document Validation
from jsvl.validations import doc_validation_set, DocValidation

# creating custom filter class for document validation
class CustomDocValidation(DocValidation):

    def validate(self, key, schema, doc, path, index, doc_is_dynamic):
        pass

# register filter in document validation set
doc_validation_set.add(CustomCheckForDocValidation())

User guide

Validating a sample document.

schema.json

{
    "cart": {
        "__data_type__": "object",
        "items*": {
            "__data_type__": "object_array",
            "title*": {
              "__case__": "__title__"
            },
            "description": {
              "__min_length__": 20
            },
            "email": {
              "__bind_regex__": "__email__"
            },
            "category*": {
              "__bind__": "category"
            },
            "keywords": {
              "__bind_regex__": "^[a-zA-Z]+$",
              "__rem__": "support only alphabets"
            },
            "quantity*": {
                "__data_type__": "integer",
                "__min_value__": 1
            },
            "discount*": {
                "__data_type__": "float",
                "__max_value__": 45.5
            }
        }
    },
    "~others": {},
    "__binder__": {
        "category": ["Health", "Fashion", "Lifestyle"]
    },
    "__defaults__": {
      "__min_value__": 100,
      "__max_value__": 1000
    }
}

document.json

{
    "cart": {
      "items": [
        {
          "title": "Product 1",
          "description": "",
          "email": "john@gmail.com",
          "quantity": 1,
          "category": "Fashion",
          "keywords": "Health",
          "discount": 30.0
        },
        {
          "title": "Product 2",
          "quantity": 4,
          "category": "Health",
          "keywords": "Health",
          "discount": 0.0
        }
      ]
    },
    "others": {
      "coords": {
        "lat": 0.022,
        "lng": 2.34
      }
    }
}

Available keywords:

Keyword Description Default Scope
* Add an asterisk keyword to the end of the key to mark it as required. false Could be add on any keyword. Excluded reserved keywords
~ Add a tilde keyword to the start of the key to bypass all the validation of the immediate child. none Could be add on any keyword. Excluded reserved keywords
__data_type__ Set data type on field, multiple data types could be supplied using pipe | for example. string|object. string object
__alow_space__ Allow space on text. true string
__min_length__ Set the minimum length. 0 string and any type of array
__max_length__ Set the maximum length. none string and any type of array
__min_value__ Set the minimum value. 0 integer and float
__max_value__ Set the maximum value. none integer and float
__case__ Apply case constraint on value.

Available case constraints:
  1. __upper__
  2. __lower__
  3. __title__
none string
__bind_regex__ Apply custom regular expression or use some pre-define. Note: __bind_regex__ will take higher precedence over __bind__ if both are defined.

Some pre-defined expressions:
  1. __email__
  2. __alpha__
  3. __numeric__
  4. __alphanumeric__
  5. __ipv4__
  6. __ipv6__
false string
__rem__ Proivde custom error when regex gets failed. false string
__bind__ Bind value from defined valueset. none ignore the data type
__binder__ This is a special keyword and that will be used only root object of the schema where you can define binding valueset. none only root object
__defaults__ This is a special keyword and that will be used to apply the defined constraints globally on the document.

Available properties that could be set globally:
  1. __allow_space__
  2. __min_length__
  3. __max_length__
  4. __min_value__
  5. __max_value__
  6. __case__
none only root object

Support Data Types

  • string
  • integer
  • float
  • bool
  • object
  • string_array
  • integer_array
  • float_array
  • bool_array
  • array

License

GPL v3

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jsvl-1.0.3.tar.gz (38.2 kB view hashes)

Uploaded Source

Built Distribution

jsvl-1.0.3-py3-none-any.whl (38.4 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page