Validate Asset JSON Schema

In this tutorial you will learn how to use JSON-Schema to validate your Assets to match the Woosmap required structure.

Prerequisites

To run this tutorial, you’ll need:

  • Python 2.7 or greater.
  • The pip package management tool.
  • Access to the internet.
  • A Woosmap account.

Validation using Schema

When you’re dealing with structured data, you need to determine whether the data is valid or not. The goal of the validation process is to determine whether the input content is correct and complete before invoking further processing.

The Validation as a separate step allow to fail fast, avoid data corruption, simplify processing code and can be integrated in tests. All validation can be done with program logic but using a Schema is more expressive and easier to understand than code.

JSON-Schema

JSON-Schema is the standard of JSON documents that describes the structure and the requirements of your JSON data. It has the widest adoption among all standards for JSON validation and many validators are available for different languages.

Validating Woosmap Assets

We use jsonschema for python to validate the assets. Simply run this command in your terminal of choice to install it using pip:

$ pip install jsonschema

Then you can validate each Asset using jsonschema.validate(asset, schema).

import json
from jsonschema import ValidationError, validate

JSON_TO_VALIDATE = 'foodmarkets.json'
WOOSMAP_SCHEMA = 'https://raw.githubusercontent.com/woosmap/woosmap-json-schema/master/asset.json'

def validate_assets(assets):
    for item in assets["stores"]:
        try:
            validate(item, {'$ref': WOOSMAP_SCHEMA })
        except ValidationError as error:
            print Exception(
                "Asset not Matching: {0}".format(error.message))
        else:
            print("...Validated Asset {id} Successful!".format(id=item["storeId"]))


def main():
    with open(file_path, 'r') as f:
        assets = load_json(JSON_TO_VALIDATE)
        validate_assets(assets)

The easiest way to get the Woosmap schema is let the RefResolver resolve the URI by defining a basic schema with $ref keyword like this: {"$ref": "http_remote_schema_path" }.

We’ve included two errors that must fail the validation process: one unauthorized Key and a Value in a wrong format. You should see these two errors when executing the script: Asset not Matching: 17630 is not of type u'string' Asset not Matching: Additional properties are not allowed (u'ErrorKey' was unexpected)



Related help articles