Contents


Use JSON Schema validation in your rich Internet application

Increase robustness with JSV and Dojo

Comments

Overview

AJAX applications depend upon JSON services conforming to expectations. Unexpected behavior can occur if services provide responses in an unexpected format or with invalid content. For complex applications, you can mitigate the risk of unexpected behavior by implementing custom routines to validate service responses. Alternatively, you can exploit JSON Schema to validate input.

JSON Schema is a draft standard that specifies a JSON-based format for defining the structure of JSON data. As of this writing, the latest is draft-03 (see Related topics).

This article compares a few of the JSON Schema validation routines. Learn to use the foremost libraries, and explore considerations and best practices for creating libraries to validate communications. The article also includes a new utility to help you write JSON Schemas.

Download the samples used in this article.

Choosing a library for your application

Choosing a library for your application can be a complex endeavor. Each application will have a different set of constraints that will affect your choice. Table 1 outlines the features of four JavaScript JSON Schema libraries.

Table 1. JSON Schema validation libraries for JavaScript
Library (Author)Draft versions supportApproximate library size
JSV: JSON Schema Validator (Gary Court)draft-01, draft-02, draft-03120KB
json-schema (Kris Zyp)draft-0310KB (requires CommonJS)
dojox.json.schema (Kris Zyp)draft-0210KB (requires Dojo)
schema.js (Andreas Kalsch)draft-02 (partial)10KB (requires CommonJS)

An application based on Dojo might use the dojox.json.schema library because it is included in the toolkit. An application that needs to support multiple versions of the (draft) standard may use JSV.

dojox.json.schema appears to be a fork of json-schema so it will be similar in usage. schema.js implements only a subset of draft-02. This article concentrates on examples for using dojox.json.schema and JSV.

Using dojox.json.schema

Listing 1 shows an HTML snippet that validates a simple object. It is designed to be injected into the head HTML element.

Listing 1. Single use of dojox.json.schema
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.7.0/dojo/dojo.js"
    type="text/javascript"></script>

<script type="text/javascript">

    require(["dojox/json/schema"], function() {
        // Object to validate
        var successObj = { 
            "foo" : "bar"
        };
        var failureObj = {
            "foo" : 1234
        };
        
        // Schema
        var schema = { 
            "type": "object",
            "properties" : {
                "foo" : {
                    "type" : "string"
                }
            }
        };
        
        // Run validation, which should succeed
        // Change this line to use failureObj to see the failure case
        var result = dojox.json.schema.validate(successObj, schema);
        
        // Check results
        if (result.valid) {
            // Success, do something
            alert("Object is valid");
        } else {
            // Failure - extract the errors array 
            var errorArr = result.errors;
            alert("property : " + errorArr[0].property + "\nmessage :  " 
                + errorArr[0].message);
        }
    });
    
</script>

Using JSV

Listing 2 is an HTML snippet that validates a simple object. It is designed to be injected into the head HTML element.

Listing 2. Single use of JSV
<!-- NB: For actual use, you should download a copy of the libraries yourself.
            github is not a CDN. -->
<script src="https://raw.github.com/garycourt/JSV/master/lib/uri/uri.js"
    type="text/javascript"></script>
<script src="https://raw.github.com/garycourt/JSV/master/lib/jsv.js"
    type="text/javascript"></script>
<script src="https://raw.github.com/garycourt/JSV/master/lib/json-schema-draft-03.js"
    type="text/javascript"></script>

<script type="text/javascript">

        // Object to validate
        var successObj = { 
            "foo" : "bar"
        };
        var failureObj = {
            "foo" : 1234
        };
        
        // Schema
        var schema = { 
            "type": "object",
            "properties" : {
                "foo" : {
                    "type" : "string"
                }
            }
        };
        
        // Run validation, which should succeed
        var env = JSV.createEnvironment("json-schema-draft-03"); 
        // Change this line to use failureObj to see the failure case
        var result = env.validate(successObj, schema);
        
        // Check result
        if (result.errors.length === 0) {
            // Success, do something
            alert("Object is valid");
        } else {
            // Failure - extract the errors array 
            var errorArr = result.errors;
            alert("uri : " + errorArr[0].uri + "\nmessage :  " 
                + errorArr[0].message);
        }

</script>

JSV provides advanced failure information in the errors array. Each error may contain the following attributes:

  • message: Human-readable error message.
  • uri: URI of the failing object location.
  • schemaUri: URI of the schema location causing failure.
  • Attribute: Schema constraint causing failure.
  • Details: Free-form array that includes further information, such as expected values.

Combining JSON Schema validation with XMLHttpRequest

If you are developing complex AJAX applications, consider using the techniques above to validate AJAX communications. Validating an object is simple when the schema is available as a JavaScript object. There is a variety of solutions for obtaining schema objects.

When writing a library to obtain schemas and validate communications, consider:

  • Overhead on page load. Preloading schemas may appear attractive but can slow down page load time.
  • Overhead on AJAX calls. Lazy-loading schemas will have an impact on the first call that uses each schema. Validating every communication could introduce performance issues. Consider applying validation to more complex services.

Writing JSON schemas

The JSON Schema definition has many nuances, so writing and testing schemas can be challenging. This article includes the JSON Schema Lint utility, which you can download, to help you create and test JSON Schema.

Hints and tips

  • The JSON Schema Internet Draft (see Related topics) has a full definition of the JSON Schema specification and is an invaluable resource. Be sure to look at the latest draft.
  • Consider using JSON Schema to assist with documenting services. Use the description attribute to describe properties.
  • When writing schemas, balance the needs of the application with validation strictness. Fully defining every attribute may make for rigorous validation, but it may also introduce fragility if the service is evolving with the application. JSON Schema allows for partial validation that can help in this area.
  • Use the advanced capabilities of JSON Schema to lock down properties. You can use additionalProperties, enum, minItems, maxItems, and so on to increase constraints.
  • When you need to allow for a property that might be multiple types, you can use an array to define these. Alternatively, use the any type.

Summary

In this article, you learned how to validate JavaScript objects against JSON Schema using two libraries. You also explored considerations for creating libraries to validate communications, and best practices when creating schemas. The article also provided a utility you can use to help create and test your own schemas.


Downloadable resources


Related topics


Comments

Sign in or register to add and subscribe to comments.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development
ArticleID=807754
ArticleTitle=Use JSON Schema validation in your rich Internet application
publish-date=04032012