JSON1

JSON Validation & Schema

Complete guide to using JSON Schema to ensure data quality and consistency

What is JSON Validation?

JSON validation is the process of ensuring that JSON data conforms to a predefined structure and rules. Through validation, we can:

  • • Ensure correct data format
  • • Verify existence of required fields
  • • Check data type matching
  • • Apply business rule constraints
  • • Provide clear error information

Benefits of Validation

  • • Improve data quality
  • • Reduce runtime errors
  • • Increase API robustness
  • • Enhance user experience
  • • Facilitate debugging and maintenance

Validation Scenarios

  • • Client input validation
  • • API interface data verification
  • • Pre-database storage validation
  • • Configuration file loading
  • • Data import/export processes

JSON Schema Fundamentals

Basic Schema Structure

Simple Schema Example

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://example.com/user.schema.json",
  "title": "User",
  "description": "User information structure",
  "type": "object",
  "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
    }
  },
  "required": ["id", "name", "email"],
  "additionalProperties": false
}

Corresponding Valid JSON Data

{
  "id": 123,
  "name": "John Doe",
  "email": "john@example.com",
  "age": 28
}

Invalid JSON Data Example

{
  "id": "abc",              // Error: should be integer
  "name": "",               // Error: length cannot be 0
  "email": "invalid-email", // Error: incorrect email format
  "age": -5                 // Error: age cannot be negative
}

Schema Keywords Explanation

Basic Keywords

$schemaSpecifies schema version
$idUnique schema identifier
titleSchema title
descriptionSchema description
typeData type

Constraint Keywords

requiredList of required fields
propertiesObject property definitions
minimumMinimum number value
maximumMaximum number value
minLengthMinimum string length

Data Type Validation

String Validation (string)

Validation Constraints

  • minLength / maxLength - Length restrictions
  • pattern - Regular expression matching
  • format - Predefined formats (email, date, uri, etc.)
  • enum - Enumerated value restrictions

Schema Example

{
  "type": "string",
  "minLength": 3,
  "maxLength": 50,
  "pattern": "^[A-Za-z0-9]+$",
  "format": "email"
}
✅ Valid Values
"user@example.com"
❌ Invalid Values
"ab"  // Insufficient length
"user@"  // Incorrect format

Number Validation (number/integer)

Validation Constraints

  • minimum / maximum - Value range
  • exclusiveMinimum / exclusiveMaximum - Exclusive range
  • multipleOf - Multiple restrictions
  • Distinction between integer vs number

Schema Example

{
  "type": "integer",
  "minimum": 1,
  "maximum": 100,
  "multipleOf": 5
}
✅ Valid Values
15, 25, 50
❌ Invalid Values
0    // Below minimum value
150  // Exceeds maximum value
13   // Not multiple of 5

Boolean Validation (boolean)

Validation Constraints

  • Only accepts true or false
  • Does not accept strings "true"/"false"
  • Does not accept numbers 1/0

Schema Example

{
  "type": "boolean"
}
✅ Valid Values
true, false
❌ Invalid Values
"true"  // String
1       // Number
null    // Null value

Array Validation (array)

Validation Constraints

  • items - Array element types
  • minItems / maxItems - Length restrictions
  • uniqueItems - Uniqueness constraint
  • additionalItems - Additional element control

Schema Example

{
  "type": "array",
  "items": {"type": "string"},
  "minItems": 1,
  "maxItems": 5,
  "uniqueItems": true
}
✅ Valid Values
["a", "b", "c"]
❌ Invalid Values
[]           // Insufficient length
["a", "a"]   // Not unique
[1, 2, 3]    // Type error

Object Validation (object)

Validation Constraints

  • properties - Property definitions
  • required - Required properties
  • additionalProperties - Additional property control
  • minProperties / maxProperties - Property count restrictions

Schema Example

{
  "type": "object",
  "properties": {
    "name": {"type": "string"}
  },
  "required": ["name"],
  "additionalProperties": false
}
✅ Valid Values
{"name": "John"}
❌ Invalid Values
{}               // Missing required field
{"name": "John", "age": 25}  // Additional properties not allowed

Error Handling Strategies

Validation Error Information Structure

{
  "valid": false,
  "errors": [
    {
      "instancePath": "/user/email",
      "schemaPath": "#/properties/user/properties/email/format",
      "keyword": "format",
      "params": {"format": "email"},
      "message": "must match format \"email\"",
      "data": "invalid-email"
    },
    {
      "instancePath": "/user/age",
      "schemaPath": "#/properties/user/properties/age/minimum",
      "keyword": "minimum", 
      "params": {"minimum": 0},
      "message": "must be >= 0",
      "data": -5
    }
  ]
}

Error Information Fields

  • instancePath: Path to erroneous data
  • schemaPath: Corresponding schema path
  • keyword: Failed validation keyword
  • params: Validation parameters
  • message: Error description
  • data: Actual erroneous data

User-Friendly Error Handling

  • • Convert technical errors to user-understandable information
  • • Provide repair suggestions
  • • Group errors by field
  • • Highlight error locations
  • • Provide correct format examples

❌ Poor Error Information

"must match format 'email'"
"data.age must be >= 0"

Problem: Technical terminology, difficult for users to understand

✅ Good Error Information

"Email format is incorrect, please enter a valid email address"
"Age cannot be negative, please enter 0 or a positive integer"

Advantage: Clear and understandable, provides solutions

Quick Reference

JSON Validation Checklist

Define complete schema
Specify required fields
Configure type constraints
Implement user-friendly error handling

Related Tools

Read this in another language