Skip to content

Instantly share code, notes, and snippets.

@sfentress
Created November 14, 2011 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sfentress/1364126 to your computer and use it in GitHub Desktop.
Save sfentress/1364126 to your computer and use it in GitHub Desktop.
JSON Schema validation + references
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JSON Schema validation + references</title>
<!-- load Dojo -->
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/dojo.xd.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojox/json/schema.js"></script>
<script>
window.onload=function() {
var schema, doc, results, text, color;
// ====== example 1 ======
schema = {
"properties": {
"topPane": {
"type": "object",
"properties": {
"height": "number"
}
},
"bottomPane": {
"$ref": "#/properties/topPane"
}
}
}
doc = {
"topPane": {
"height": 10
},
"bottomPane": {
"height": "not-a-number"
}
}
results = dojox.json.schema.validate(doc, schema);
if (results.valid) {
text = "Validator says json is valid, but it ought to be invalid";
color = "red"
} else {
text = "Validator correctly says json is invalid";
color = "green"
}
document.getElementById("result1").innerHTML = text;
document.getElementById("result1").setAttribute("style", "border: "+color+" solid 1px")
// ====== example 2 ======
schema = {
"properties": {
"topPane": {
"$ref": "#/paneSchema"
},
"bottomPane": {
"$ref": "#/paneSchema"
}
},
"paneSchema": {
"type": "object",
"properties": {
"height": "number"
}
}
}
doc = {
"topPane": {
"height": 10
},
"bottomPane": {
"height": "not-a-number"
}
}
results = dojox.json.schema.validate(doc, schema);
if (results.valid) {
text = "Validator says json is valid, but it ought to be invalid";
color = "red"
} else {
text = "Validator correctly says json is invalid";
color = "green"
}
document.getElementById("result2").innerHTML = text;
document.getElementById("result2").setAttribute("style", "border: "+color+" solid 1px")
}
</script>
</head>
<body>
<h3>Result 1</h3>
Later properties referring to the subschemas of earlier properties:
<div id="result1"></div>
<h3>Result 2</h3>
Defining the subschemas of all three properties separately:
<div id="result2"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment