Briefly About JSON Schema and the use of it

JSON (JavaScript Object Notation) is a lightweight data-interchange format and undeniably one of the most popular formats for exchanging data on the web and its meta description JSON Schema it’s getting more popular nowadays.

The main use of JSON Schema is to describe the structure and validate your JSON documents. Today we have access to vast number of tools that enabling us to generate JSON Schema based on our own JSON documents, one of the example:

We can easily convert a JSON document into JSON Scheme. For instance we have a product JSON:

{
“id”: 12331,
“name”: “Mountain Bike”,
“currency”: “USD”,
“price”: 599.99,
“category”: [
“transport”,
“sports”,
“outdoor”
]
}

Once you processed you will get something like this:

{
“$schema”: “http://json-schema.org/draft-04/schema#",
“definitions”: {},
“id”: “http://example.com/example.json",
“properties”: {
“category”: {
“items”: {
“type”: “string”
},
“type”: “array”
},
“currency”: {
“type”: “string”
},
“id”: {
“type”: “integer”
},
“name”: {
“type”: “string”
},
“price”: {
“type”: “number”
}
},
“type”: “object”
}

Say you want all the properties to be a compulsory, you can simply add in required tag right before the “type” tag as such below:

“required”: [
“category”,
“currency”,
“price”,
“id”,
“name”
],
“type”: “object”

Interface will look like this…

Once we have our schema created, we can use it to validate our JSON document, such as in our API. There are many tools suggested by 
json-schema.org, one of the popular PHP validator

The snippet of code below give you an idea how to validate input JSON against the schema created earlier.

<?php

$data = json_decode(file_get_contents('data.json'));

// Validate
$validator = new JsonSchema\Validator;
$validator->validate($data, (object)['$ref' => 'file://' . realpath('schema.json')]);

if ($validator->isValid()) {
echo "The supplied JSON validates against the schema.\n";
} else {
echo "JSON does not validate. Violations:\n";
foreach ($validator->getErrors() as $error) {
echo sprintf("[%s] %s\n", $error['property'], $error['message']);
}
}

Apart from that you can also generate markdown schema for documentation purpose. Assumed that you are in centos terminal:

npm is prerequisite, so you might need to install it

sudo yum install npm
sudo npm install jsonschema-md -g

To generate mark-down schema is as easy as:

$ jsonschema-md my_schema.json > my_schema.md

Output: my_schema.md as below:

# My Product
#### Type: object
__Production descriptions__
| Name | Type | Description | Example |
| — — — — | — — — — | — — — — — — | — — — — |
| id | integer | | |
| name | string | | |
| currency | string | | |
| price | number | | |
| category | array | | |
*****

Graphical representation:

Above just a glimpse of what the JSON Schema can do, learn more at http://json-schema.org/