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 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 support | Approximate library size |
|---|---|---|
| JSV: JSON Schema Validator (Gary Court) | draft-01, draft-02, draft-03 | 120KB |
| json-schema (Kris Zyp) | draft-03 | 10KB (requires CommonJS) |
| dojox.json.schema (Kris Zyp) | draft-02 | 10KB (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.
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>
|
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.
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.
- 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
descriptionattribute 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
anytype.
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.
| Description | Name | Size | Download method |
|---|---|---|---|
| Sample, showing use of dojox.json.schema | dojox_json_schema-example.html | 2KB | HTTP |
| Sample, showing use of JSV | jsv-example.html | 2KB | HTTP |
| Utility for creating and testing JSON Schema | jsonschema.zip | 140KB | HTTP |
Information about download methods
Learn
-
JSON Schema: Learn more about the
latest schemas, tools, and discussion.
-
A JSON
Media Type for Describing the Structure and Meaning of JSON
Documents: Read the latest JSON Schema Internet Draft (a working
document of the Internet Engineering Task Force (IETF).
-
Documentation for dojox.json.schema: Learn how dojox.json.schema
implements JSON Schema to provide data validation against JSON Schemas.
-
Gary Court's JSV library:
Learn more about this JavaScript implementation of an extendable, fully
compliant JSON Schema Validator.
-
Andreas Kalsch's schema.js
library: Get more information about this sophisticated JSON Schema-based data validation and adaptation.
-
Kris Zyp's json-schema
library: Read about JSON Schema specifications, reference schemas,
and a CommonJS implementation.
- developerWorks Web
development zone: Find articles covering various web-based
solutions. See the Web
development technical library for a wide range of technical
articles and tips, tutorials, standards, and IBM Redbooks.
- developerWorks
technical events and webcasts: Stay current with technology in
these sessions.
- developerWorks Live! briefings: Get up to speed quickly on IBM
products and tools as well as IT industry trends.
-
developerWorks on-demand demos: Watch demos ranging from product
installation and setup for beginners, to advanced functionality for
experienced developers.
- developerWorks on
Twitter: Join today to follow developerWorks tweets.
Get products and technologies
-
IBM product
evaluation versions: Download or explore
the online trials in the IBM SOA Sandbox and get your hands on
application development tools and middleware products from DB2, Lotus,
Rational, Tivoli, and WebSphere.
Discuss
- developerWorks
community: Connect with other developerWorks users while exploring
the developer-driven blogs, forums, groups, and wikis.
- Find other developerWorks members interested in web development.

Nick 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.




