JSON Validation: How to Validate and Fix JSON Data

23 Jun 2026 1,089 words

JSON Validation: How to Validate and Fix JSON Data

JSON (JavaScript Object Notation) is the most widely used data interchange format on the web. From API responses to configuration files, JSON is everywhere. But JSON is strict about its syntax — a single misplaced comma or missing quote can break an entire parser. This guide covers everything you need to know about JSON validation, common errors, and how to fix them.

Why JSON Validation Matters

Invalid JSON can cause a variety of problems:

  • API failures: A server returning invalid JSON will crash client-side parsers and break applications.
  • Configuration errors: Broken JSON in configuration files (like package.json, composer.json, or tsconfig.json) can prevent tools from running.
  • Data corruption: Importing or exporting data with JSON errors can lead to silent data loss.
  • Debugging headaches: Tracing invalid JSON in large files without proper tools is time-consuming and error-prone.

Validating JSON before using it in production saves time and prevents bugs. A good validator checks not only syntax but also structural consistency.

What Makes JSON Valid or Invalid?

JSON syntax follows strict rules. Here are the most common validation requirements:

Valid JSON Rules

  • Strings must be enclosed in double quotes (single quotes are not allowed).
  • Keys must be double-quoted strings (unquoted identifiers are invalid).
  • Numbers can be integers or decimals, but leading zeros are not allowed (e.g., 01 is invalid).
  • Boolean values must be lowercase: true, false.
  • Null values must be lowercase: null.
  • No trailing commas are allowed in objects or arrays.
  • Comments are not allowed in standard JSON.

Example of Valid JSON

{
  "name": "Alice",
  "age": 30,
  "isActive": true,
  "roles": ["admin", "editor"],
  "address": {
    "city": "New York",
    "zip": "10001"
  }
}

Example of Invalid JSON

{
  name: "Alice",       // Missing quotes around key
  'age': 30,           // Single quotes instead of double
  "isActive": true,    // Trailing comma
  "roles": ["admin"],, // Double comma
  "note": undefined    // undefined is not valid JSON
}

Common JSON Errors

Error Example Fix
Trailing comma [1, 2,] Remove the comma after the last item: [1, 2]
Single quotes {'key': 'value'} Use double quotes: {"key": "value"}
Missing quotes on keys {key: "value"} Add quotes: {"key": "value"}
Unescaped control characters "line\nbreak" unescaped Escape as "line\\nbreak"
Comments // this is a comment Remove all comments before parsing
Trailing garbage [1, 2]extra Remove text after the closing bracket
Missing closing bracket {"key": "value" Add the closing }
Extra closing bracket {"key": "value"}} Remove the extra }
Invalid number format 01, 1., .5 Use valid numbers: 1, 1.0, 0.5
Multiple JSON objects {"a":1}{"b":2} Wrap in array: [{"a":1},{"b":2}] or parse separately

How to Validate JSON

Online JSON Validator

The easiest way to validate JSON is using an online tool. The JSON Validator & Repair tool on Help2Code checks your JSON syntax in real time and provides detailed error messages that point directly to the problem location.

Features include:

  • Real-time validation as you type or paste
  • Line and column numbers for each error
  • Human-readable error descriptions
  • Automatic repair suggestions for common issues
  • Option to minify or beautify the output
  • JSON schema validation support

Validating JSON in Code

JavaScript (Browser / Node.js):

try {
  const data = JSON.parse(jsonString);
  console.log('Valid JSON:', data);
} catch (error) {
  console.error('Invalid JSON:', error.message);
}

Python:

import json

def validate_json(data):
    try:
        json.loads(data)
        return True, None
    except json.JSONDecodeError as e:
        return False, str(e)

is_valid, error = validate_json('{"name": "Alice"}')
print(error if not is_valid else "Valid!")

PHP:

function validateJson($string) {
    json_decode($string);
    return json_last_error() === JSON_ERROR_NONE;
}

Command Line (jq):

# Validate JSON file (returns exit code 0 if valid)
jq . file.json > /dev/null && echo "Valid" || echo "Invalid"

# Show the specific error
jq . file.json 2>&1

JSON Schema Validation

Beyond syntax validation, JSON Schema defines the structure and data types your JSON should follow. A JSON Schema is itself a JSON document that describes:

  • Required and optional fields
  • Data types (string, number, boolean, array, object, null)
  • String patterns and formats (email, date, URI)
  • Minimum and maximum values for numbers
  • Array length constraints

The JSON Schema Validator tool on Help2Code lets you validate your JSON data against a schema to ensure structural correctness.

Example JSON Schema:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "required": ["name", "email"],
  "properties": {
    "name": {
      "type": "string",
      "minLength": 1
    },
    "email": {
      "type": "string",
      "format": "email"
    },
    "age": {
      "type": "integer",
      "minimum": 0,
      "maximum": 150
    }
  }
}

How to Repair Invalid JSON

Some JSON errors can be automatically repaired. Common repair strategies include:

  1. Remove trailing commas: Strip any commas before closing brackets or braces.
  2. Add missing quotes: Automatically quote unquoted keys and single-quoted strings.
  3. Fix escaped characters: Correct improperly escaped control characters.
  4. Remove comments: Strip JavaScript-style comments (both // and /* */).
  5. Convert single quotes to double quotes: Replace all single-quoted strings with double-quoted strings.
  6. Remove trailing garbage: Trim any text after the last closing bracket or brace.

The JSON Validator & Repair tool automatically applies these fixes and shows you the repaired JSON alongside the original.

Best Practices for Working With JSON

  • Always validate before parsing: Never assume external JSON data is valid. Always wrap parsing in error handling.
  • Use a linter in your editor: Most code editors have JSON linters that highlight errors as you type.
  • Pretty print for readability: Formatted JSON is easier to validate visually. Use 2-space indentation as the standard.
  • Avoid manual editing of large JSON files: Use tools to programmatically generate or modify JSON to prevent human error.
  • Use JSON Schema for API contracts: Define and enforce the expected structure of your JSON data with schemas.
  • Keep JSON files under version control: Configuration files and test fixtures benefit from git history and code review.

Conclusion

JSON validation is an essential skill for any developer working with modern web technologies. Understanding the syntax rules, common errors, and available tools helps you catch and fix problems early. Use the JSON Validator & Repair tool to instantly check your JSON, and always validate external data before trusting it in your applications.


About this article

Learn how to validate JSON data, common JSON errors, and how to use online validators to detect and repair invalid JSON.


Related Articles


Related Tools