Home → How to Validate JSON

How to Validate JSON: Complete Guide with Tools & Examples (2026)

📅 Updated March 2026 ⏱ 8 min read 🛠 Practical guide

Invalid JSON is one of the most frustrating developer errors — a misplaced comma or a missing bracket can break an entire API request or config file. This guide covers exactly how to validate JSON: from quick online checks to code-level validation with JSON Schema.

Validate your JSON right now

Free online validator — paste your JSON and see errors instantly with line numbers.

Open JSON Validator →

Two Types of JSON Validation

When someone says "validate JSON," they usually mean one of two things:

  1. Syntax validation — Is the JSON well-formed? Does it follow the JSON grammar rules? Can a parser read it without errors?
  2. Schema validation — Is the JSON the right shape? Does it have the expected fields, types, and constraints defined by a JSON Schema?

You need syntax validation first — invalid syntax means no schema can even be applied. Then schema validation confirms the data structure matches your expectations.

The 10 Most Common JSON Errors

These are the mistakes that cause the vast majority of invalid JSON:

1 Trailing commas

Invalid: trailing comma after the last item

{
  "name": "Alice",
  "age": 28,   ← trailing comma — NOT allowed in JSON
}

Valid: no comma after the last item

{
  "name": "Alice",
  "age": 28
}

2 Single quotes instead of double quotes

// Invalid:
{ 'name': 'Alice' }

// Valid:
{ "name": "Alice" }

JSON requires double quotes. Single quotes are a JavaScript convention, but JSON is stricter.

3 Unquoted property keys

// Invalid (JavaScript object literal syntax):
{ name: "Alice", age: 28 }

// Valid JSON:
{ "name": "Alice", "age": 28 }

4 Missing commas between properties

// Invalid:
{
  "name": "Alice"
  "age": 28       ← missing comma after "Alice"
}

// Valid:
{
  "name": "Alice",
  "age": 28
}

5 Comments (not supported in JSON)

// Invalid — JSON does not support comments:
{
  "name": "Alice",  // user's full name
  "age": 28         /* age in years */
}

// Valid — remove comments:
{
  "name": "Alice",
  "age": 28
}

6 Unescaped special characters in strings

// Invalid — raw newline/tab in string:
{ "message": "Hello
World" }

// Valid — use escape sequences:
{ "message": "Hello\nWorld" }

Characters that must be escaped inside JSON strings: \" (double quote), \\ (backslash), \/ (slash), \n (newline), \r (carriage return), \t (tab), \b (backspace), \f (form feed), \uXXXX (unicode).

7 Using undefined, NaN, or Infinity

// Invalid — JavaScript-specific values not in JSON spec:
{ "value": undefined }
{ "ratio": NaN }
{ "limit": Infinity }

// Valid alternatives:
{ "value": null }
{ "ratio": null }
{ "limit": 1.7976931348623157e+308 }

8 Mismatched brackets or braces

// Invalid — array opened with [ but closed with }:
{ "items": [1, 2, 3} }

// Valid:
{ "items": [1, 2, 3] }

9 Numbers with leading zeros

// Invalid — leading zeros not allowed (except 0.x):
{ "code": 007 }

// Valid:
{ "code": 7 }

10 Empty input or non-JSON root

// Invalid — JSON must start with { or [ at root:
hello world

// Valid roots:
{ "key": "value" }
[1, 2, 3]
"just a string"   ← valid but unusual
42                ← valid but unusual

How to Validate JSON Online

The fastest way to validate JSON is with an online tool:

  1. Go to the JSON Validator
  2. Paste your JSON into the input box
  3. Click Validate (or just type — it validates as you type)
  4. If there are errors, the tool shows you the line number and a description of the error
  5. Fix the errors and re-validate

Pro tip: Use the JSON Formatter on your JSON first. Proper indentation makes it much easier to spot mismatched brackets and missing commas visually.

Validate JSON from the Command Line

Using Python (built-in, any OS)

# Validate and pretty-print in one command:
python3 -m json.tool your-file.json

# If valid: prints formatted JSON
# If invalid: SyntaxError with line number and description

# Example with piped input:
echo '{"name": "Alice", "age": 28}' | python3 -m json.tool

Using jq (Linux/macOS/Windows)

# Install: brew install jq (macOS), apt install jq (Linux)
jq . your-file.json

# Quick null check (just validate, no output):
jq empty your-file.json && echo "Valid" || echo "Invalid"

Using Node.js

node -e "JSON.parse(require('fs').readFileSync('data.json', 'utf8')); console.log('Valid')"

Using curl (validate API response)

# Validate JSON from an API endpoint:
curl -s https://api.example.com/data | python3 -m json.tool

Validate JSON in Code

JavaScript / TypeScript

function isValidJSON(str: string): boolean {
  try {
    JSON.parse(str);
    return true;
  } catch {
    return false;
  }
}

// With error details:
function validateJSON(str: string): { valid: boolean; error?: string } {
  try {
    JSON.parse(str);
    return { valid: true };
  } catch (e) {
    return { valid: false, error: (e as Error).message };
  }
}

Python

import json

def is_valid_json(s: str) -> bool:
    try:
        json.loads(s)
        return True
    except json.JSONDecodeError:
        return False

# With error details:
def validate_json(s: str):
    try:
        data = json.loads(s)
        return {"valid": True, "data": data}
    except json.JSONDecodeError as e:
        return {"valid": False, "error": str(e), "line": e.lineno, "col": e.colno}

Go

import (
    "encoding/json"
    "fmt"
)

func isValidJSON(s string) bool {
    var js json.RawMessage
    return json.Unmarshal([]byte(s), &js) == nil
}

// Usage:
if !isValidJSON(input) {
    fmt.Println("Invalid JSON")
}

JSON Schema Validation (Advanced)

Syntax validation only checks if JSON is parseable. Schema validation checks if the data has the right structure: correct field names, types, required fields, value ranges, and patterns.

A JSON Schema is itself a JSON document that describes the expected shape:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["id", "name", "email"],
  "properties": {
    "id":    { "type": "integer", "minimum": 1 },
    "name":  { "type": "string", "minLength": 1, "maxLength": 100 },
    "email": { "type": "string", "format": "email" },
    "age":   { "type": "integer", "minimum": 0, "maximum": 150 },
    "role":  { "type": "string", "enum": ["admin", "user", "guest"] }
  },
  "additionalProperties": false
}

Against this schema:

// Valid:
{ "id": 1, "name": "Alice", "email": "alice@example.com" }

// Invalid — missing required "email":
{ "id": 2, "name": "Bob" }

// Invalid — "role" not in enum:
{ "id": 3, "name": "Carol", "email": "c@c.com", "role": "superadmin" }

// Invalid — "age" exceeds maximum:
{ "id": 4, "name": "Dave", "email": "d@d.com", "age": 200 }

Try it: Use the JSON Schema Validator to validate any JSON against a schema, or the JSON Schema Generator to auto-generate a schema from your JSON data.

Validate JSON Schema in JavaScript

// Using Ajv (npm install ajv)
import Ajv from 'ajv';

const ajv = new Ajv();
const schema = {
  type: 'object',
  required: ['id', 'name'],
  properties: {
    id:   { type: 'integer' },
    name: { type: 'string' }
  }
};

const validate = ajv.compile(schema);
const valid = validate({ id: 1, name: 'Alice' });

if (!valid) {
  console.log(validate.errors);
  // [{ message: "must have required property 'name'", ... }]
}

Validate JSON in CI/CD Pipelines

Prevent invalid JSON from reaching production by adding validation to your pipeline:

# GitHub Actions example
- name: Validate JSON files
  run: |
    for file in $(find . -name "*.json" -not -path "*/node_modules/*"); do
      python3 -m json.tool "$file" > /dev/null && echo "✅ $file" || echo "❌ $file"
    done

Quick Reference: JSON Validation Methods

MethodBest ForSpeed
Online validatorQuick one-off checks, debuggingInstant
python3 -m json.toolFiles, API responses in terminalFast
jq .Files + piped dataFast
JSON.parse()JavaScript/Node.js codeNative
json.loads()Python codeNative
JSON Schema (Ajv, etc.)API contract validation, testsFast
CI/CD pipeline scriptAutomated checks in Git hooksPer commit

Validate your JSON now

Free, instant JSON validation with clear error messages and line numbers.

Open JSON Validator →

Frequently Asked Questions

What is JSON validation? +
JSON validation has two levels. Syntax validation checks that the JSON is well-formed — correct brackets, double quotes, commas, and no unsupported features like comments or trailing commas. Schema validation checks that the JSON follows a defined structure — correct field names, types, and required fields as defined in a JSON Schema document.
Why is my JSON invalid? +
The most common causes: (1) trailing comma after the last item in an object or array, (2) single quotes instead of double quotes, (3) unquoted property keys, (4) missing commas between properties, (5) JavaScript-style comments (// or /* */), (6) using undefined, NaN, or Infinity (not valid JSON values), (7) unescaped special characters inside strings.
How do I validate JSON in JavaScript? +
Wrap JSON.parse() in a try/catch block: try { JSON.parse(str); return true; } catch { return false; }. For schema validation, use Ajv or Zod libraries to compile a schema and validate data against it.
What is the difference between JSON syntax validation and JSON Schema validation? +
Syntax validation checks if the text is valid JSON that any parser can read. Schema validation goes further — it checks if the parsed JSON matches a specific structure (required fields, correct types, value ranges). You always need syntax validation first, then optionally schema validation.
Can I validate JSON from the command line? +
Yes. Python's built-in JSON module is available on all platforms: python3 -m json.tool yourfile.json. It prints formatted JSON if valid, or a syntax error with line number if not. You can also use jq . yourfile.json or node -e "JSON.parse(require('fs').readFileSync('f.json','utf8'))".
Does JSON allow trailing commas? +
No. Standard JSON does not allow trailing commas. This is one of the most common JSON errors. Some tools and editors (like VS Code's settings.json) support JSONC (JSON with Comments) which does allow trailing commas, but a strict JSON parser like JSON.parse() will reject them.

Related Tools & Guides

JSON Validator  |  JSON Formatter  |  JSON Schema Validator  |  JSON Schema Tutorial  |  JSONPath Cheatsheet  |  JSON Repair Tool