JSONValidationBest Practices

How to Validate JSON – Best Practices

March 5, 2026·5 min read

Invalid JSON is the silent killer of API integrations. A single missing comma or mismatched bracket can crash a deployment, corrupt a database import, or silently swallow webhook events. Proper JSON validation catches these errors at the source — before they reach production.

1. Two Levels of JSON Validation

JSON validation has two distinct levels:

Level 1: Syntax Validation

Is the JSON structurally valid? Checks for: balanced braces/brackets, properly quoted keys, no trailing commas, no undefined values, correct number formats.

Level 2: Schema Validation

Does the JSON match the expected structure? Checks: required fields present, correct data types, value ranges, string formats (email, URL, date), array constraints.

2. Syntax Validation in Code

JavaScript

function isValidJson(str) {
  try {
    JSON.parse(str);
    return true;
  } catch {
    return false;
  }
}

// With error details
function parseJsonSafely(str) {
  try {
    return { data: JSON.parse(str), error: null };
  } catch (e) {
    return { data: null, error: e.message };
  }
}

const result = parseJsonSafely('{"name": "Alice",}');
// { data: null, error: "Unexpected token }" }

Python

import json

def validate_json(text: str) -> tuple[bool, str]:
    try:
        json.loads(text)
        return True, "Valid JSON"
    except json.JSONDecodeError as e:
        return False, f"Error at line {e.lineno}, col {e.colno}: {e.msg}"

valid, msg = validate_json('{"name": "Alice"}')
# (True, "Valid JSON")

valid, msg = validate_json('{"name": "Alice",}')
# (False, "Error at line 1, col 18: Trailing comma...")

3. JSON Schema Validation

JSON Schema is a vocabulary for annotating and validating JSON documents. It allows you to define the exact structure, types, and constraints your data must meet.

// Schema definition
const userSchema = {
  type: "object",
  required: ["id", "name", "email"],
  properties: {
    id:    { type: "integer", minimum: 1 },
    name:  { type: "string", minLength: 1, maxLength: 100 },
    email: { type: "string", format: "email" },
    roles: {
      type: "array",
      items: { type: "string", enum: ["admin", "editor", "viewer"] }
    },
    active: { type: "boolean" }
  },
  additionalProperties: false
};

In JavaScript, use the Ajv library (the fastest JSON Schema validator):

import Ajv from 'ajv';
import addFormats from 'ajv-formats';

const ajv = new Ajv();
addFormats(ajv);

const validate = ajv.compile(userSchema);

const user = { id: 1, name: "Alice", email: "[email protected]", active: true };
const valid = validate(user);

if (!valid) {
  console.error(validate.errors);
  // [{ instancePath: '/email', message: 'must match format "email"' }]
}

In Python, use jsonschema:

from jsonschema import validate, ValidationError

schema = { "type": "object", "required": ["name"], "properties": {
  "name": { "type": "string" } }
}

try:
    validate(instance={"name": "Alice"}, schema=schema)
    print("Valid!")
except ValidationError as e:
    print(f"Invalid: {e.message}")

4. Common Validation Mistakes

Only checking syntax, not semantics

A JSON with all strings is syntactically valid even if the "age" field contains "twenty-three" instead of 23. Use JSON Schema to enforce types.

Not validating external data

Any JSON coming from an external source (API response, user upload, webhook) must be validated before use.

Ignoring error line numbers

When JSON fails to parse, always log the line and column of the error for fast debugging.

Not validating in CI

Add JSON lint checks to your CI pipeline to catch invalid config files before deployment.

5. JSON Validation in CI/CD

# GitHub Actions: validate all JSON files in the repo
- name: Validate JSON files
  run: |
    find . -name "*.json" -not -path "*/node_modules/*" | while read f; do
      python -c "import json, sys; json.load(open('$f'))" || exit 1
      echo "✅ $f"
    done

6. Conclusion

JSON validation is a two-step process: syntax first, schema second. Use JSON.parse() or json.loads() for basic syntax checking, and JSON Schema + Ajv/jsonschema for semantic validation. Integrate both into your CI pipeline to catch errors before they reach production.

Use our free JSON Validator for instant browser-based syntax validation with line-level error details.