How to Validate Your JSON Using JSON Schema

Drag to rearrange sections
Rich Text Content

The following scenario is possible: You and your colleague are creating a JSON with some results. Your job is to create a JSON containing some results and then send it to your colleague. Her task is to read the JSON and then save it in the database. Each of you agreed verbally on the types and keys, and each implemented their respective parts. It sounds legit and will work, if the JSON structure remains simple. One day, you sent the wrong key and discovered a bug. The lesson was learned and you created an API. You also documented it on your favorite documentation platform. You can now both have a look at the API to ensure you've implemented it correctly.

How to validate JSON Data before you import it into a database. - Simple  Talk

But is that enough? Let's suppose you actually implement it correctly. Let's suppose another colleague made a change. Now it returns an array instead of one number. Everything breaks when your teammate doesn't know about your API.

Imagine if your JSON could be validated directly in the code, before it is sent and before it is parsed. This is JSON schema!

This post will explain JSON Schema and its power, as well as how it can be used in various scenarios.

What is JSON Schema and how do I use it?

JSON Schema, a JSON-based format that defines the structure of JSON data, is called JSON Schema. It defines the JSON data required for an application and how to interact. It is used to validate, document, hyperlink navigation and control interaction with JSON data.

You can either define the schema in a JSON file and load it into your code, or you can create it directly in your code.

Why should I use JSON Schema

Each JSON object follows a key-value structure. The key is a string. The value can be any type - number string, array, JSON generator etc.

Some cases allow the value to be limited to a particular type. In other cases the value can be more flexible. Some keys in our JSON have to be present, while others are optional. You can also have more complex scenarios. If we have a key, for example, then another key must be created. A second key value can have a dependent effect on the value of one key.

JSON Schema can validate and test all of these scenarios. It allows you to validate your JSON and ensure it meets API requirements before integrating it with other services.

Summary

JSON Schema can be a powerful tool. You can validate your JSON structure, and ensure it conforms to the API. It is possible to create as many schemas as you want, as long as you have the required requirements. It can be added to your code either as an extra test or during run-time.

This post outlines the basics and explains some of the more complicated options. You can find a lot more to learn and use.

 

rich_text    
Drag to rearrange sections
Rich Text Content
rich_text    

Page Comments