Table of Contents
Using JSON Schema in VS Code - Example
VS Code can automatically validate JSON files against a schema and show errors
if the data is incorrect.
Follow these steps to use JSON Schema validation in VS Code.
1. Create a JSON Schema File (orderSchema.json)
First, create a schema and save it as orderSchema.json.
This schema will validate order data.
2. Create a JSON File (order.json)
Now, create a JSON file and save it as order.json.
By adding $schema, VS Code will automatically validate the data against the
schema.
Since "$schema": "./orderSchema.json" is added:
VS Code automatically validates the data against the schema.
If there are errors, VS Code will highlight them immediately.
3. Alternative: Define Schema in VS Code Settings
If you don’t want to add $schema in your JSON files,
you can configure VS Code to apply the schema automatically in
settings.json.
Steps:
- Open
settings.jsonin VS Code
- Press
Ctrl + Shift + P - Search for "Preferences: Open Settings (JSON)" and select it
- Add the following setting:
What does this do?
- When you open
order.json, VS Code automatically validates it usingorderSchema.json. - If the JSON is invalid, VS Code will display errors immediately.
4. Invalid JSON Example & VS Code Warnings
The following JSON is invalid because:
"orderId"has an incorrect format"paymentMethod"is"Bitcoin", which is not allowed
VS Code will show these errors:
"orderId"does not match the required format (should be 8 characters long)."paymentMethod"cannot be"Bitcoin"(allowed values:"Credit Card","PayPal","Bank Transfer").
SUMMARY
- Create a JSON schema (
orderSchema.json). - Prepare a JSON file (
order.json). - Use
$schemaor configuresettings.jsonin VS Code to enable validation. - VS Code will automatically highlight errors and guide you to fix them.
Now, you can validate JSON files easily in VS Code!