Validate Asset JSON Schema

  1. Prerequisites
  2. Validation using Schema
  3. JSON-Schema
  4. Validating Woosmap Assets

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:

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:

Shell
        $ pip install jsonschema

    

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

Python
        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