2026-03-05•3 min read•by DevUtilz
JSON Validator and Linter Guide
JSONValidationToolsTutorial
JSON Validator and Linter Guide
Validating JSON ensures your data is correctly formatted before processing.
Basic Validation
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}
// Usage
console.log(isValidJSON('{"name":"John"}')); // true
console.log(isValidJSON('{name:John}')); // false
Detailed Error Messages
function validateJSON(str) {
try {
const parsed = JSON.parse(str);
return { valid: true, data: parsed };
} catch (e) {
const match = e.message.match(/position (\d+)/);
const position = match ? parseInt(match[1]) : null;
return {
valid: false,
error: e.message,
position
};
}
}
Using ajv for Schema Validation
import Ajv from 'ajv';
const ajv = new Ajv();
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'integer' },
email: { type: 'string', format: 'email' }
},
required: ['name', 'email']
};
const validate = ajv.compile(schema);
const data = { name: 'John', age: 30, email: 'john@example.com' };
const valid = validate(data);
if (!valid) {
console.log(validate.errors);
}
Common JSON Errors
| Error | Cause | Fix | |-------|-------|-----| | Unexpected token | Invalid character | Check for typos | | Unexpected end | Unclosed bracket | Count your [] | | Missing comma | Between elements | Add commas | | Trailing comma | After last item | Remove it | | Single quotes | Only double allowed | Use " not ' |
Formatter + Validator
function formatAndValidate(str) {
try {
const parsed = JSON.parse(str);
return {
valid: true,
formatted: JSON.stringify(parsed, null, 2)
};
} catch (e) {
return { valid: false, error: e.message };
}
}
CLI Tools
# Validate JSON
cat file.json | python -m json.tool
# Pretty print
node -e "console.log(JSON.stringify(JSON.parse(require('fs').readFileSync(0)), null, 2))"
# jq
cat file.json | jq .
Online Validators
- jsonlint.com
- jsonformatter.curiousconcept.com
- jsonvalidator.org
Best Practices
- Validate at input - Check JSON before processing
- Validate at output - Ensure correct format
- Use schemas - For complex data structures
- Add validation in CI - Catch errors early
Lint Rules
// Example: no-trailing-commas
// Invalid
{
"name": "John",
}
// Valid
{
"name": "John"
}
Schema Example
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"username": {
"type": "string",
"minLength": 3,
"maxLength": 30
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
}
},
"required": ["username", "email"]
}
Conclusion
Always validate JSON before processing. Use schema validation for complex data. Add validation in your build process and CI pipeline.