CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-github-fge--json-schema-validator

A comprehensive Java implementation of the JSON Schema validation specification supporting both draft v4 and v3 with complete validation capabilities and extensibility.

Pending
Overview
Eval results
Files

cli.mddocs/

Command Line Interface

Command-line tools for JSON Schema validation from the command line with various output formats and options. The CLI provides convenient access to validation functionality for scripts, automation, and interactive use.

Capabilities

Main CLI Class

Entry point for command-line JSON Schema validation.

/**
 * Main class for command-line JSON Schema validation
 */
public final class Main {
    /**
     * Command-line entry point for JSON Schema validation
     * @param args Command-line arguments
     */
    public static void main(String... args);
}

Return Codes

Standardized exit codes for CLI operations.

/**
 * Exit codes for command-line validation operations
 */
enum RetCode {
    /**
     * Validation completed successfully (exit code 0)
     */
    ALL_OK(0),
    
    /**
     * Command-line usage error (exit code 2)
     */
    CMD_ERROR(2),
    
    /**
     * Instance validation failed (exit code 100)
     */
    VALIDATION_FAILURE(100),
    
    /**
     * Schema syntax error detected (exit code 101)
     */
    SCHEMA_SYNTAX_ERROR(101);
    
    /**
     * Get numeric exit code
     * @return int exit code value
     */
    int get();
}

Reporter Interface

Interface for formatting and outputting validation results.

/**
 * Interface for reporting validation results in different formats
 */
public interface Reporter {
    /**
     * Report validation results
     * @param report ProcessingReport containing validation results
     * @throws IOException if output writing fails
     */
    void reportValidation(ProcessingReport report) throws IOException;
}

Reporters Factory

Factory for creating different types of result reporters.

/**
 * Factory for creating validation result reporters
 */
public final class Reporters {
    /**
     * Create default console reporter
     * @return Reporter that outputs to standard output
     */
    public static Reporter getDefault();
    
    /**
     * Create JSON format reporter
     * @return Reporter that outputs JSON formatted results
     */
    public static Reporter getJSON();
    
    /**
     * Create brief format reporter
     * @return Reporter that outputs minimal validation results
     */
    public static Reporter getBrief();
}

Command Line Usage

Basic Validation

# Validate instance against schema
java -jar json-schema-validator.jar schema.json instance.json

# Using Maven exec plugin
mvn exec:java -Dexec.mainClass="com.github.fge.jsonschema.main.cli.Main" \
    -Dexec.args="schema.json instance.json"

# Using Gradle
gradle run --args="schema.json instance.json"

Command Line Options

# Basic validation (schema and instance)
java -jar json-schema-validator.jar schema.json instance.json

# Brief output (only show validation status OK/NOT OK)
java -jar json-schema-validator.jar --brief schema.json instance.json
java -jar json-schema-validator.jar -s schema.json instance.json

# Quiet mode (no output, only exit codes)
java -jar json-schema-validator.jar --quiet schema.json instance.json
java -jar json-schema-validator.jar -q schema.json instance.json

# Validate multiple instances against same schema
java -jar json-schema-validator.jar schema.json instance1.json instance2.json

# Syntax validation only (validate schema syntax)
java -jar json-schema-validator.jar --syntax schema.json

# Set fake root for URI resolution
java -jar json-schema-validator.jar --fakeroot http://example.com/ schema.json instance.json

# Help information
java -jar json-schema-validator.jar --help

Exit Codes

  • 0 (ALL_OK): Validation successful, all instances are valid
  • 2 (CMD_ERROR): Invalid command-line usage
  • 100 (VALIDATION_FAILURE): One or more instances failed validation
  • 101 (SCHEMA_SYNTAX_ERROR): Schema has syntax errors

Usage Examples

Example 1: Basic CLI Validation Script

#!/bin/bash
# validate-json.sh - JSON validation script

SCHEMA_FILE="$1"
INSTANCE_FILE="$2"

if [ $# -ne 2 ]; then
    echo "Usage: $0 <schema-file> <instance-file>"
    exit 1
fi

if [ ! -f "$SCHEMA_FILE" ]; then
    echo "Error: Schema file '$SCHEMA_FILE' not found"
    exit 1
fi

if [ ! -f "$INSTANCE_FILE" ]; then
    echo "Error: Instance file '$INSTANCE_FILE' not found"
    exit 1
fi

echo "Validating $INSTANCE_FILE against $SCHEMA_FILE..."

java -jar json-schema-validator-2.2.6-lib.jar "$SCHEMA_FILE" "$INSTANCE_FILE"
exit_code=$?

case $exit_code in
    0)
        echo "✓ Validation successful"        
        ;;
    2)
        echo "✗ Command line error"
        ;;
    100)
        echo "✗ Validation failed"
        ;;
    101)
        echo "✗ Schema syntax error"
        ;;
    *)
        echo "✗ Unknown error (exit code: $exit_code)"
        ;;
esac

exit $exit_code

Example 2: Batch Validation Script

#!/bin/bash
# batch-validate.sh - Validate multiple files against a schema

SCHEMA_FILE="$1"
shift
INSTANCE_FILES=("$@")

if [ -z "$SCHEMA_FILE" ] || [ ${#INSTANCE_FILES[@]} -eq 0 ]; then
    echo "Usage: $0 <schema-file> <instance-file1> [instance-file2] ..."
    exit 1
fi

echo "Schema: $SCHEMA_FILE"
echo "Validating ${#INSTANCE_FILES[@]} instance(s)..."
echo

overall_success=true

for instance in "${INSTANCE_FILES[@]}"; do
    echo -n "Validating $instance... "
    
    java -jar json-schema-validator-2.2.6-lib.jar "$SCHEMA_FILE" "$instance" --brief > /dev/null 2>&1
    exit_code=$?
    
    case $exit_code in
        0)
            echo "✓ VALID"
            ;;
        2)
            echo "✗ CMD ERROR"
            overall_success=false
            ;;
        100)
            echo "✗ INVALID"
            overall_success=false
            ;;
        101)
            echo "✗ SCHEMA ERROR"
            overall_success=false
            ;;
        *)
            echo "✗ ERROR ($exit_code)"
            overall_success=false
            ;;
    esac
done

echo
if $overall_success; then
    echo "All validations passed"
    exit 0
else
    echo "Some validations failed"
    exit 1
fi

Example 3: Integration with CI/CD Pipeline

# .github/workflows/validate-schemas.yml
name: Validate JSON Schemas

on: [push, pull_request]

jobs:
  validate:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v2
    
    - name: Set up Java
      uses: actions/setup-java@v2
      with:
        java-version: '8'
        distribution: 'adopt'
    
    - name: Download JSON Schema Validator
      run: |
        wget https://github.com/fge/json-schema-validator/releases/download/2.2.6/json-schema-validator-2.2.6-lib.jar
    
    - name: Validate API Schemas
      run: |
        for schema in schemas/*.json; do
          echo "Validating schema: $schema"
          java -jar json-schema-validator-2.2.6-lib.jar --syntax-only "$schema"
          if [ $? -ne 0 ]; then
            echo "Schema validation failed for $schema"
            exit 1
          fi
        done
    
    - name: Validate Test Data
      run: |
        for data in test-data/*.json; do
          echo "Validating data: $data against schemas/api-schema.json"
          java -jar json-schema-validator-2.2.6-lib.jar schemas/api-schema.json "$data"
          if [ $? -ne 0 ]; then
            echo "Data validation failed for $data"
            exit 1
          fi
        done

Example 4: JSON Output Processing

#!/bin/bash
# validate-with-json-output.sh - Process JSON validation results

SCHEMA_FILE="$1"
INSTANCE_FILE="$2"

# Get JSON formatted validation results
json_output=$(java -jar json-schema-validator-2.2.6-lib.jar \
    --json "$SCHEMA_FILE" "$INSTANCE_FILE" 2>/dev/null)
exit_code=$?

if [ $exit_code -eq 0 ]; then
    echo "Validation successful"
else
    echo "Validation failed. Details:"
    
    # Use jq to format and extract error information if available
    if command -v jq >/dev/null 2>&1; then
        echo "$json_output" | jq -r '.[] | "  Error at \(.instance.pointer): \(.message)"'
    else
        echo "$json_output"
    fi
fi

exit $exit_code

Example 5: Custom Reporter Implementation

import com.github.fge.jsonschema.main.cli.Reporter;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.core.report.ProcessingMessage;

/**
 * Custom reporter that outputs validation results in CSV format
 */
public class CSVReporter implements Reporter {
    
    @Override
    public void reportValidation(ProcessingReport report) throws IOException {
        System.out.println("Status,Level,Instance,Schema,Message");
        
        if (report.isSuccess()) {
            System.out.println("SUCCESS,INFO,,,Validation passed");
        } else {
            for (ProcessingMessage message : report) {
                JsonNode messageJson = message.asJson();
                String level = message.getLevel().toString();
                String instancePath = messageJson.path("instance").path("pointer").asText("");
                String schemaPath = messageJson.path("schema").path("pointer").asText("");
                String text = message.getMessage().replace(",", ";"); // Escape commas
                
                System.out.printf("FAILURE,%s,\"%s\",\"%s\",\"%s\"%n", 
                    level, instancePath, schemaPath, text);
            }
        }
    }
}

// Usage in custom CLI application
public class CustomCLI {
    public static void main(String[] args) throws Exception {
        JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
        JsonNode schema = loadJsonFromFile(args[0]);
        JsonNode instance = loadJsonFromFile(args[1]);
        
        JsonSchema jsonSchema = factory.getJsonSchema(schema);
        ProcessingReport report = jsonSchema.validate(instance);
        
        Reporter csvReporter = new CSVReporter();
        csvReporter.reportValidation(report);
        
        System.exit(report.isSuccess() ? 0 : 100);
    }
}

Maven Integration

Using as Build Plugin

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>3.0.0</version>
    <executions>
        <execution>
            <id>validate-schemas</id>
            <phase>test</phase>
            <goals>
                <goal>java</goal>
            </goals>
            <configuration>
                <mainClass>com.github.fge.jsonschema.main.cli.Main</mainClass>
                <arguments>
                    <argument>${project.basedir}/src/main/resources/schema.json</argument>
                    <argument>${project.basedir}/src/test/resources/test-data.json</argument>
                </arguments>
            </configuration>
        </execution>
    </executions>
</plugin>

Ant Integration

<target name="validate-json">
    <java jar="lib/json-schema-validator-2.2.6-lib.jar" 
          fork="true" 
          failonerror="true">
        <arg value="schemas/api-schema.json"/>
        <arg value="data/sample-data.json"/>
    </java>
</target>

CLI Best Practices

  1. Exit Codes: Always check exit codes in scripts for proper error handling
  2. Output Formats: Use appropriate output formats (brief, JSON) based on your needs
  3. Batch Processing: Validate multiple files efficiently using shell loops
  4. Error Handling: Implement proper error handling and reporting in automation scripts
  5. CI Integration: Include schema validation in continuous integration pipelines
  6. Performance: For large-scale validation, consider programmatic API over CLI
  7. Documentation: Document your validation scripts and their expected behavior

Install with Tessl CLI

npx tessl i tessl/maven-com-github-fge--json-schema-validator

docs

basic-validation.md

cli.md

configuration.md

extensions.md

format-validation.md

index.md

syntax-validation.md

tile.json