What is Json schema

Json is very flexible, especially when you expect a json payload you have to ensure that data is passed in correct data type. For instance

Json Payload 1 – amount as number

{
item : “premaseem”,
sold : true
amount : 786
}

Json Payload 2 – id as string

{
item : “premaseem”,
sold: “True”
amount : “786”
}

Both payloads are good however if you have to do some calculation on amount and if it is passed as string, math operation would fail. So you need to publish a schema by which user or consumer can understand what data type is expected to create a valid and useful payload which can be consumed without causing issues.

This website can be used to generate the Json schema

http://jsonschema.net

This website can be used to validate the json object against Json schema

http://json-schema-validator.herokuapp.com

What is JSON Schema ?

JSON Schema specifies a JSON-based format to define the structure of JSON data for validation, documentation, and interaction control. A JSON Schema provides a contract for the JSON data required by a given application, and how that data can be modified.

JSON Schema is based on the concepts from XML Schema (XSD), but is JSON-based. The JSON data schema can be used to validate JSON data. As in XSD, the same serialization/deserialization tools can be used both for the schema and data. The schema is self-describing.

Example JSON Schema (draft 4):

{
  "$schema": "http://json-schema.org/schema#",
  "title": "Product",
  "type": "object",
  "required": ["id", "name", "price"],
  "properties": {
    "id": {
      "type": "number",
      "description": "Product identifier"
    },
    "name": {
      "type": "string",
      "description": "Name of the product"
    },
    "price": {
      "type": "number",
      "minimum": 0
    },
    "tags": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "stock": {
      "type": "object",
      "properties": {
        "warehouse": {
          "type": "number"
        },
        "retail": {
          "type": "number"
        }
      }
    }
  }
}

The JSON Schema above can be used to test the validity of the JSON code below:

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}