Home

Awesome

json-gate

json-gate validates JSON objects against a JSON schema. In other words, it makes sure an object conforms to the type and structure that your code expects. For example, a server can use it to ensure input received from a client conforms to the API.

The JSON schema can also help with documentation and collaboration. Copy it to your API document and everybody should understand exactly what is expected.

json-gate likes you! It is...

What's a JSON schema?

JSON Schema is a proposed Internet draft defining a JSON media type (application/schema+json) with the following goals:

json-gate supports most of JSON Schema Draft 3, minus the hyperlinking and hyper schema parts.

Example

var createSchema = require('json-gate').createSchema;

var schema = createSchema({
	type: 'object',
	properties: {
		query: {
			type: 'string',
            minLength: 1,
            maxLength: 64,
			required: true
		},
		maxResults: {
			type: 'integer',
			maximum: 20,
			default: 10
		}
	},
    additionalProperties: false
});

try {
    schema.validate(input);
} catch(err) {
    return res.send(400, err); // 400 Bad Request
}

This schema is explained below in the Hello, schema section.

Installation

$ npm install json-gate

Usage

json-gate.createSchema(jsonSchema)

This function gets a JSON Schema definition and returns a new Schema object. It verifies that the schema is valid. If the latter is malformed an error will be thrown pinpointing the problem.

Schema.validate(jsonObject)

This function gets a JSON object and validates it against the schema. If the JSON object does not conform to the schema an error will be thrown (or returned, see Synchronous/Asynchronous below).

The function stops after encountering an error. It does not return multiple errors. The function does not return a value. Be aware that the input JSON object may be edited in-place if the default attribute is used.

Errors

The error messages are human-friendly and detailed. For example: "JSON object property 'user.password': length is 3 when it should be at least 6". Ready to be shrink-wrapped in a 400 Bad Request response and shipped to the client!

Equaly helpful error messages are produced in the case of a malformed schema, to assist you during development. For example: "Schema property 'num': 'exclusiveMaximum' attribute is a number when it should be a boolean".

Synchronous/Asynchronous

Schema.validate can be called in two ways, to suit your needs:

It should be noted that the JSON object passed to the callback function is the same as the input JSON object. It is only passed for convenience. Any default values used will affect the original JSON object, even when calling asynchronously.

Hello, schema

A JSON schema is defined using a JavaScript object containing various attributes.

Let's start by analyzing the schema given in the example above. What does it say about the JSON object?

JSON Schema properties can be nested: objects and arrays include other attributes, which may themselves be objects and arrays. Notice that objects' properties are unordered, whereas array items are ordered.

See Attributes section below to learn about more possibilities.

Attributes

Below are all the supported attributes.

Terminology: in this section, instance refers to a JSON value (object or property) that the schema will be describing and validating.

type

Defines the expected instance type. It can take one of two forms:

Example - instance should be either a string or null:

type: ['string', 'null']

The default is 'any'.

disallow

Defines the disallowed instance type. This is the opposite of type. It can take one of two forms:

required

A boolean indicating whether an instance is mandatory (true) or optional (false).

Example with a mandatory property and an optional one:

{
    type: 'object',
    properties: {
        query: {
            type: 'string',
            required: true
        },
        safeSearch: {
            type: 'string',
            enum: ['off', 'moderate', 'strict']
        }
    }
}

The default is false (optional).

default

Defines the default value of the instance when the instance is undefined.

Example:

maxResults: {
    type: 'integer',
    default: 10
}

The JSON object is edited in-place. In other words, the default values are set to the original JSON object, not a returned copy.

enum

An array containing all possible values. The instance must equal one of the values.

Example:

enum: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']

properties

Applies only to instances of type 'object'.

Defines the properties of the instance object. The properties attribute is an object, matching properties to their valid schema.

Example:

{
    type: 'object',
    properties: {
        name: { type: 'string' },
        age: { type: 'integer' }
    }
}

The default is an empty object.

Note: Properties are considered unordered, the order of the instance properties may be in any order.

patternProperties

Applies only to instances of type 'object'.

This attribute is similar to the properties attribute, but the keys are regular expression patterns instead of property names. Any instance property whose name fits a pattern must be valid against the appropriate schema.

Example:

{
    type: 'object',
    patternProperties: {
        '^sz': { type: 'string' },
        '^n': { type: 'number' },
        '^b': { type: 'boolean' }
    }
}

Note that using this attribute may cause instances to be validated more than once:

additionalProperties

Applies only to instances of type 'object'.

Defines a schema for all properties that are not explicitly defined by properties and do not match any pattern in patternProperties. It can take one of two forms:

Example:

{
    type: 'object',
    properties: {
        id: 'integer',
        name: 'string'
    },
    patternProperties: {
        '^_debug': { type: 'any' }
    },
    additionalProperties: false
}

The default is an empty schema, which allows any value for additional properties.

dependencies

Applies only to instances of type 'object'.

This attribute is an object, matching properties to their requirements. If the instance object has a property with the same name as a property in the dependencies attribute object, then the instance must comply with the requirement.

The requirement can take one of three forms:

items

Applies only to instances of type 'array'.

Defines the items of the instance array. It can take one of two forms:

additionalItems

Applies only to instances of type 'array', and only together with the tuple typing form of the items attribute.

additionalItems defines the behavior when there are more items in the instance array than in the items array. It can take one of two forms:

Example - a string, an integer and the rest are booleans:

{
    type: 'array',
    items: [
        { type: 'string' },
        { type: 'integer' }
    ],
    additionalItems: { type: 'boolean' }
}

The default is an empty schema, which allows additional items of any type.

minItems

Applies only to instances of type 'array'.

Defines the minimum number of values in an array.

maxItems

Applies only to instances of type 'array'.

Defines the maximum number of values in an array.

uniqueItems

Applies only to instances of type 'array'.

A boolean that indicates whether all items in the array instance must be unique (contains no two identical values).

minLength

Applies only to instances of type 'string'.

Defines the minimum length of the string.

maxLength

Applies only to instances of type 'string'.

Defines the maximum length of the string.

pattern

Applies only to instances of type 'string'.

A string containing a regular expression. The instance string must match it.

Example:

youtubeVideoId: {
    type: 'string',
    pattern: '^[A-Za-z0-9_-]{11}$'
}

minimum

Applies only to instances of type 'number'.

Defines the minimum value of the instance property.

exclusiveMinimum

Applies only to instances of type 'number', and only together with the minimum attribute.

Defines the behavior of the minimum attribute:

Example:

rand: {
    type: 'number',
    minimum: 0,
    exclusiveMinimum: false,
    maximum: 1,
    exclusiveMaximum: true
}

The default is false.

maximum

Applies only to instances of type 'number'.

Defines the maximum value of the instance property.

exclusiveMaximum

Applies only to instances of type 'number', and only together with the maximum attribute.

Defines the behavior of the maximum attribute:

Example:

rand: {
    type: 'number',
    minimum: 0,
    exclusiveMinimum: false,
    maximum: 1,
    exclusiveMaximum: true
}

The default is false.

divisibleBy

Applies only to instances of type 'number'.

Defines what value the number instance must be divisible by with no remainder. This value may not be 0.

format

Applies only to instances of types 'string' or 'number'.

Defines the expected instance format.

Available formats:

Note: Unknown formats are silently ignored.

title

A string that provides a short description of instance property.

It allows to document the JSON schema. It has no effect on the validation process.

Example:

postalPlusFourCode: {
    title: 'ZIP+4 code',
    description: 'Zip+4 code: 5 digits dash 4 digits',
    type: 'string',
    pattern: '^[0-9]{5}-[0-9]{4}$'
}

description

A string that provides a full description of the purpose of the instance property.

It allows to document the JSON schema. It has no effect on the validation process.

Example:

{
    description: 'A person',
    type: 'object',
    properties: {
        name: { type: 'string' },
        age: { type: 'integer' }
    }
}

License

(The MIT License)

Copyright (c) 2012 Ofer Reichman

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.