How to Validate JSON in Python and JavaScript
Validating JSON means two different things depending on context: checking that a string is syntactically well-formed JSON, and checking that the parsed data matches an expected structure. This guide covers both levels of validation in Python and JavaScript, the two languages most commonly used together in modern API and automation workflows.
Syntax validation in Python
Python's built-in json module raises json.JSONDecodeError when a string is not valid JSON. Wrap the call in a try/except block to handle it cleanly:
import json
def is_valid_json(raw_string):
try:
json.loads(raw_string)
return True
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e.msg} at line {e.lineno}, column {e.colno}")
return False
is_valid_json('{"name": "Rahul", "age": 25}') # True
is_valid_json('{"name": "Rahul", "age": 25,}') # False - trailing commaSyntax validation in JavaScript
JavaScript's JSON.parse() throws a SyntaxError for the same kinds of malformed input. The equivalent pattern using try/catch:
function isValidJson(rawString) {
try {
JSON.parse(rawString);
return true;
} catch (err) {
console.error('Invalid JSON:', err.message);
return false;
}
}
isValidJson('{"name": "Rahul", "age": 25}'); // true
isValidJson("{'name': 'Rahul', 'age': 25}"); // false - single quotesStructural validation with a schema (Python)
Syntax validation alone does not guarantee the data has the fields you expect. Use the jsonschema library in Python to validate structure and types:
from jsonschema import validate, ValidationError
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0}
},
"required": ["name", "age"]
}
data = {"name": "Rahul", "age": 25}
try:
validate(instance=data, schema=schema)
print("Valid data")
except ValidationError as e:
print(f"Validation failed: {e.message}")Structural validation with a schema (JavaScript)
In Node.js, the Ajv library provides the equivalent schema validation, and is significantly faster than hand-written validation logic:
const Ajv = require('ajv');
const ajv = new Ajv();
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'integer', minimum: 0 }
},
required: ['name', 'age']
};
const validate = ajv.compile(schema);
const data = { name: 'Rahul', age: 25 };
if (validate(data)) {
console.log('Valid data');
} else {
console.log(validate.errors);
}Best practices for both languages
- Never trust external JSON input — always validate before using it in business logic or database queries.
- Separate syntax validation (is it parseable) from schema validation (does it have the right shape).
- Return clear, specific error messages so API consumers know exactly what field failed validation.
- Cache compiled schema validators (like Ajv's compile step) instead of recompiling on every request.
Frequently Asked Questions
Use json.loads() inside a try/except block that catches json.JSONDecodeError. If the string parses successfully it is syntactically valid JSON; for structural validation use a library like jsonschema.
Use JSON.parse() inside a try/catch block that catches SyntaxError. For deeper structural validation against a schema, use a library like Ajv with a JSON Schema definition.
Syntax validation only checks that a string is well-formed JSON, such as matching brackets and quoted keys. Schema validation goes further and checks that specific fields exist, have the correct types, and meet constraints like required values.