🐍 JSON Validation with Python (JSON Validator Tutorial)
What is JSON Validation?
In web development and data interaction, JSON (JavaScript Object Notation) is one of the most commonly used data formats.
It's used for API communication, configuration files, log storage, and more.
However, during development, we often encounter:
- • JSON file format errors;
- • Unclosed brackets;
- • Missing string quotes;
- • Extra commas, etc.
These errors can prevent programs from parsing JSON data, so before using it in production, we need to validate that the JSON format is correct.
Using Python to Validate JSON Format
Python has a very practical built-in module called json that can easily handle JSON loading and validation.
✅ Example 1: Basic Validation
import json
def validate_json(json_string):
try:
json.loads(json_string)
print("✅ JSON format is correct!")
except json.JSONDecodeError as e:
print("❌ JSON format error:", e)
# Example JSON
data = '{"name": "Alice", "age": 25}'
validate_json(data)Output:
✅ JSON format is correct!If the input format is incorrect, for example:
data = '{"name": "Alice", "age": 25,}' # Extra comma
validate_json(data)Result:
❌ JSON format error: Expecting property name enclosed in double quotes: line 1 column 28 (char 27)✅ Example 2: Validating JSON Files
import json
def validate_json_file(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
try:
json.load(f)
print(f"✅ JSON format in file {file_path} is correct!")
except json.JSONDecodeError as e:
print(f"❌ {file_path} format error: {e}")
# Usage
validate_json_file('data.json')This script will automatically read the file and validate whether the content is valid JSON.
Enhanced Validation: Checking Structure and Fields
Beyond syntax correctness, sometimes we also want to validate that the JSON structure meets expectations, such as requiring name, age, and email fields.
We can use the third-party library jsonschema for this.
Installation:
pip install jsonschemaExample:
from jsonschema import validate, ValidationError
# Define data structure
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"email": {"type": "string"}
},
"required": ["name", "age"]
}
# Test data
data = {"name": "Alice", "age": 25}
try:
validate(instance=data, schema=schema)
print("✅ JSON data structure is valid!")
except ValidationError as e:
print("❌ JSON structure error:", e.message)Output:
✅ JSON data structure is valid!If fields are missing or types are incorrect, clear error messages will be displayed.
Complete Example: Batch File Validator
import os
import json
def validate_json_files(folder):
for file in os.listdir(folder):
if file.endswith('.json'):
path = os.path.join(folder, file)
try:
with open(path, 'r', encoding='utf-8') as f:
json.load(f)
print(f"✅ {file} validation passed")
except json.JSONDecodeError as e:
print(f"❌ {file} format error: {e}")
# Batch validate all JSON files in current directory
validate_json_files(".")Conclusion
Using Python to validate JSON is not only simple and efficient, but can also be integrated with automated testing, data import, and other workflows.
You can use JSON validation as an independent step in your project to avoid interface exceptions caused by format errors in production environments.
If you don't want to run scripts manually, you can also use our online tool directly:
It supports:
- • Online formatting and validation
- • One-click beautification and compression
- • Conversion to CSV / XML
- • Automatic fixing of common syntax errors
🔖 Related Articles
JSON Work Team January 15, 2025