JSON Validator

What is JSON Validation?

JSON (JavaScript Object Notation) validation is the process of checking whether a JSON string conforms to the proper JSON syntax rules. A valid JSON must follow strict formatting rules, and even small syntax errors can make the entire JSON invalid.

JSON Syntax Rules

JSON is built on two main structures:

  • A collection of name/value pairs (object)
  • An ordered list of values (array)

1. Basic JSON Structure

{
  "name": "value",
  "array": [1, 2, 3],
  "object": {
    "nested": "property"
  }
}

2. Data Types

JSON supports six data types:

String

  • Must be enclosed in double quotes
  • Can contain Unicode characters
  • Supports escape sequences
{
  "simple": "Hello World",
  "unicode": "Hello 世界",
  "escaped": "Line 1\nLine 2\tTabbed",
  "quotes": "She said \"Hello\""
}

Number

  • Integer or floating point
  • Can be negative
  • Supports scientific notation
{
  "integer": 42,
  "negative": -17,
  "decimal": 3.14159,
  "scientific": 1.23e-4,
  "zero": 0
}

Boolean

  • Only true or false (lowercase)
{
  "isActive": true,
  "isDeleted": false
}

null

  • Represents empty value
  • Must be lowercase
{
  "data": null,
  "optional": null
}

Object

  • Collection of key/value pairs
  • Keys must be strings in double quotes
  • Values can be any JSON data type
{
  "user": {
    "id": 123,
    "name": "John Doe",
    "active": true,
    "profile": {
      "email": "[email protected]",
      "preferences": null
    }
  }
}

Array

  • Ordered list of values
  • Values can be any JSON data type
  • Can be empty
{
  "numbers": [1, 2, 3, 4, 5],
  "mixed": ["string", 42, true, null],
  "objects": [
    {"id": 1, "name": "Alice"},
    {"id": 2, "name": "Bob"}
  ],
  "nested": [[1, 2], [3, 4]],
  "empty": []
}

3. Syntax Requirements

String Formatting

  • All strings must use double quotes (not single quotes)
  • Property names must be quoted strings
// ✅ Correct
{
  "name": "John",
  "age": 30
}

// ❌ Incorrect
{
  'name': 'John',    // Single quotes not allowed
  name: "John",      // Unquoted keys not allowed
  "age": 30,
}

Trailing Commas

  • Not allowed in JSON
// ✅ Correct
{
  "name": "John",
  "age": 30
}

// ❌ Incorrect
{
  "name": "John",
  "age": 30,    // Trailing comma not allowed
}

Comments

  • Not supported in standard JSON
// ❌ Incorrect - Comments not allowed
{
  "name": "John",  // This is a comment
  /* This is also not allowed */
  "age": 30
}

Common JSON Validation Errors

1. Syntax Errors

Missing Quotes

// ❌ Error
{
  name: "John"
}

// ✅ Fixed
{
  "name": "John"
}

Single Quotes

// ❌ Error
{
  'name': 'John'
}

// ✅ Fixed
{
  "name": "John"
}

Trailing Comma

// ❌ Error
{
  "name": "John",
  "age": 30,
}

// ✅ Fixed
{
  "name": "John",
  "age": 30
}

Missing Comma

// ❌ Error
{
  "name": "John"
  "age": 30
}

// ✅ Fixed
{
  "name": "John",
  "age": 30
}

2. Structure Errors

Unmatched Brackets

// ❌ Error
{
  "users": [
    {"name": "John"},
    {"name": "Jane"
  ]
}

// ✅ Fixed
{
  "users": [
    {"name": "John"},
    {"name": "Jane"}
  ]
}

Invalid Escape Sequences

// ❌ Error
{
  "path": "C:\folder\file.txt"
}

// ✅ Fixed
{
  "path": "C:\\folder\\file.txt"
}

3. Data Type Errors

Invalid Numbers

// ❌ Error
{
  "hex": 0xFF,        // Hexadecimal not allowed
  "infinity": Infinity, // Infinity not allowed
  "nan": NaN          // NaN not allowed
}

// ✅ Fixed
{
  "hex": 255,
  "infinity": null,
  "nan": null
}

Undefined Values

// ❌ Error
{
  "value": undefined
}

// ✅ Fixed
{
  "value": null
}

Validation Examples

Example 1: User Profile

{
  "user": {
    "id": 12345,
    "username": "johndoe",
    "email": "[email protected]",
    "firstName": "John",
    "lastName": "Doe",
    "age": 28,
    "isActive": true,
    "lastLogin": "2024-01-15T10:30:00Z",
    "preferences": {
      "theme": "dark",
      "language": "en-US",
      "notifications": {
        "email": true,
        "push": false,
        "sms": null
      }
    },
    "roles": ["user", "editor"],
    "metadata": null
  }
}

Example 2: API Response

{
  "status": "success",
  "code": 200,
  "message": "Data retrieved successfully",
  "data": {
    "products": [
      {
        "id": "prod_001",
        "name": "Laptop",
        "price": 999.99,
        "currency": "USD",
        "inStock": true,
        "categories": ["electronics", "computers"],
        "specifications": {
          "weight": 2.1,
          "dimensions": {
            "width": 30.5,
            "height": 2.0,
            "depth": 21.5
          },
          "warranty": "2 years"
        }
      }
    ],
    "pagination": {
      "page": 1,
      "limit": 10,
      "total": 100,
      "hasNext": true
    }
  },
  "timestamp": "2024-01-15T10:30:00.000Z"
}

Example 3: Configuration File

{
  "application": {
    "name": "MyApp",
    "version": "1.2.3",
    "environment": "production"
  },
  "database": {
    "host": "localhost",
    "port": 5432,
    "name": "myapp_db",
    "ssl": true,
    "connections": {
      "min": 5,
      "max": 20
    }
  },
  "features": {
    "authentication": true,
    "analytics": false,
    "beta": null
  },
  "supportedLanguages": ["en", "es", "fr", "de"],
  "maintenance": {
    "enabled": false,
    "message": "",
    "scheduledAt": null
  }
}

Best Practices for JSON Validation

1. Development Guidelines

  • Use proper indentation for readability
  • Validate JSON regularly during development
  • Use descriptive property names in camelCase or snake_case
  • Keep consistent data types for similar properties

2. Error Handling

  • Implement proper error handling for JSON parsing
  • Provide meaningful error messages to users
  • Log validation errors for debugging

3. Performance Considerations

  • Validate JSON structure before processing data
  • Use streaming parsers for large JSON files
  • Implement size limits to prevent memory issues

4. Security Best Practices

  • Validate input size to prevent DoS attacks
  • Sanitize data after JSON parsing
  • Use schema validation for API endpoints
  • Never execute JSON content as code

JSON Schema Validation

For more advanced validation, consider using JSON Schema:

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

Tools and Resources

Online Validators

  • JSONLint.com
  • JSON Formatter & Validator
  • JSON Schema Validator

Command Line Tools

# Using jq to validate JSON
jq . input.json

# Using Python
python -m json.tool input.json

# Using Node.js
node -e "JSON.parse(require('fs').readFileSync('input.json', 'utf8'))"

IDE Extensions

  • JSON validation in VS Code
  • JSONBuddy for Windows
  • JSON Editor plugins

Conclusion

JSON validation is crucial for:

  • Data integrity in applications
  • API communication reliability
  • Configuration management accuracy
  • Error prevention in data processing

Always validate JSON data before processing to ensure your applications handle data correctly and provide better user experiences.