Use JSON Schema validation in your rich Internet application

Increase robustness with JSV and Dojo

Complex AJAX applications can interact with hundreds of different JSON services, thus introducing requirements for client-side validation. This article compares a few of the JSON Schema validation libraries. Learn how to use the libraries to validate your JSON objects. As a bonus, download a sample utility to help you write your own schemas and validate objects against them.

Nick Maynard, Web 2.0 Consultant, IBM

Author photoNick Maynard works for the Business Solutions Team at the IBM Software Lab in Hursley, United Kingdom. He specializes in Dojo, Ajax, web programming, web services, and Linux. You can contact Nick at nick.maynard@uk.ibm.com.



03 April 2012

Also available in Chinese Russian Japanese

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.

Frequently used abbreviations

  • HTML: HyperText Markup Language
  • JSON: JavaScript Object Notation
  • JSV: JSON Schema Validator

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 Resources).

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="http://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 Resources) 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.


Downloads

DescriptionNameSize
Sample, showing use of dojox.json.schemadojox_json_schema-example.html2KB
Sample, showing use of JSVjsv-example.html2KB
Utility for creating and testing JSON Schemajsonschema.zip140KB

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


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