DEV Community

loading...

How to validate a JSON file with JSON Schema

Maxime Guilbert
Just a dev who touches a lot of things and wants to share his experiences. (or just want to note somewhere things to don't forget)
・1 min read

These days, I'm regularly checking big JSON files and I was tired to have to check every field manually. So I've searched on internet if we can have a JSON file structure validation.

And I found json-schema.org!


What is it?

JSON Schema is a specification to validate the structure of the JSON file with a schema.

Schema example

{
    "type" : "object",
    "properties" : 
       "price" : {"type" : "number"},
       "name" : {"type" : "string"}
    }
}
Enter fullscreen mode Exit fullscreen mode

As you can see, a schema is a JSON file where you will define all your fields with their type. Then, you can use it with an implementation of a validator and check all your related files!


Validators

In the website, you can see a huge list of validators for a lot of languages/contexts.

Alt Text

The one that I like is a python one :

GitHub logo Julian / jsonschema

An(other) implementation of JSON Schema for Python

jsonschema

PyPI version Supported Python versions Build status ReadTheDocs status

jsonschema is an implementation of JSON Schema for Python.

>>> from jsonschema import validate

>>> # A sample schema, like what we'd get from json.load()
>>> schema = {
...     "type" : "object",
...     "properties" : {
...         "price" : {"type" : "number"},
...         "name" : {"type" : "string"},
...     },
... }

>>> # If no exception is raised by validate(), the instance is valid.
>>> validate(instance={"name" : "Eggs", "price" : 34.99}, schema=schema)

>>> validate(
...     instance={"name" : "Eggs", "price" : "Invalid"}, schema=schema,
... )                                   # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
    ...
ValidationError: 'Invalid' is not of type 'number'
Enter fullscreen mode Exit fullscreen mode

It can also be used from console:

$ jsonschema --instance sample.json sample.schema
Enter fullscreen mode Exit fullscreen mode

Features

  • Full…

Also, if you look a little bit further, you will see other tools to help you to create a schema.


Finally, I hope it will help you as much as it helps me.

Discussion (0)