RapidJSON (Validation)

C++JSONValidationJSON SchemaHigh PerformancePerformance

GitHub Overview

Tencent/rapidjson

A fast JSON parser/generator for C++ with both SAX/DOM style API

Stars14,763
Watchers557
Forks3,606
Created:March 4, 2014
Language:C++
License:Other

Topics

None

Star History

Tencent/rapidjson Star History
Data as of: 7/19/2025, 04:31 AM

RapidJSON (Validation)

Overview

RapidJSON is a high-performance C++ JSON library developed by Tencent. It provides both SAX and DOM style APIs with built-in JSON Schema validation functionality. Through zero-copy optimizations, it achieves extremely high performance and is widely used in performance-critical applications such as game servers and real-time systems.

Features

  • High-speed Parsing: Industry-leading JSON parsing performance
  • JSON Schema Support: Built-in JSON Schema Draft v4 validation
  • Memory Efficient: Reduced memory usage through zero-copy optimizations
  • SAX/DOM Support: Support for both streaming processing and tree structures
  • Full Unicode Support: Supports UTF-8, UTF-16, and UTF-32
  • Header-only: Easy integration

Usage Examples

Basic JSON Schema Validation

#include "rapidjson/document.h"
#include "rapidjson/schema.h"
#include "rapidjson/stringbuffer.h"

using namespace rapidjson;

// JSON schema definition
const char* schemaJson = R"({
    "type": "object",
    "required": ["name", "age"],
    "properties": {
        "name": {
            "type": "string",
            "minLength": 1
        },
        "age": {
            "type": "integer",
            "minimum": 0,
            "maximum": 150
        },
        "email": {
            "type": "string",
            "format": "email"
        }
    }
})";

// Execute validation
Document schemaDoc;
schemaDoc.Parse(schemaJson);

SchemaDocument schema(schemaDoc);
SchemaValidator validator(schema);

// Target JSON for validation
Document targetDoc;
targetDoc.Parse(R"({
    "name": "John Doe",
    "age": 30,
    "email": "[email protected]"
})");

// Validation
if (!targetDoc.Accept(validator)) {
    // Get error information
    StringBuffer sb;
    validator.GetInvalidSchemaPointer().StringifyUriFragment(sb);
    printf("Invalid schema: %s\n", sb.GetString());
    
    printf("Invalid keyword: %s\n", validator.GetInvalidSchemaKeyword());
    
    sb.Clear();
    validator.GetInvalidDocumentPointer().StringifyUriFragment(sb);
    printf("Invalid document: %s\n", sb.GetString());
}

Custom Validation

// Custom validator implementation
class CustomValidator {
    Document schema;
    
public:
    bool ValidateConfig(const char* json) {
        Document doc;
        doc.Parse(json);
        
        if (doc.HasParseError()) {
            return false;
        }
        
        // Check required fields
        if (!doc.HasMember("version") || !doc["version"].IsString()) {
            return false;
        }
        
        // Validate version format
        std::regex versionRegex(R"(^\d+\.\d+\.\d+$)");
        if (!std::regex_match(doc["version"].GetString(), versionRegex)) {
            return false;
        }
        
        // Validate nested objects
        if (doc.HasMember("settings")) {
            const Value& settings = doc["settings"];
            if (!settings.IsObject()) {
                return false;
            }
            
            // Range check for configuration values
            if (settings.HasMember("timeout")) {
                if (!settings["timeout"].IsNumber() || 
                    settings["timeout"].GetDouble() < 0 || 
                    settings["timeout"].GetDouble() > 3600) {
                    return false;
                }
            }
        }
        
        return true;
    }
};

Performance Optimization

// High-speed processing with in-situ parsing
class FastJsonProcessor {
    static constexpr size_t kBufferSize = 65536;
    char buffer[kBufferSize];
    
public:
    bool ProcessLargeJsonFile(const char* filename) {
        FILE* fp = fopen(filename, "rb");
        if (!fp) return false;
        
        FileReadStream is(fp, buffer, sizeof(buffer));
        
        // In-situ parsing to avoid string copying
        Document doc;
        doc.ParseStream<kParseInsituFlag>(is);
        
        fclose(fp);
        
        if (doc.HasParseError()) {
            return false;
        }
        
        // Process document
        return ProcessDocument(doc);
    }
    
private:
    bool ProcessDocument(const Document& doc) {
        // Validation and data processing
        return true;
    }
};

Comparison & Alternatives

Comparison with Similar Libraries

  • nlohmann/json: More user-friendly API but lower performance
  • simdjson: Read-only but even faster parsing
  • Boost.JSON: Better integration with Boost ecosystem

When to Choose RapidJSON

  • When performance is the highest priority
  • When JSON Schema validation is required
  • When processing large amounts of JSON data
  • When minimizing memory usage is important

Learning Resources

Summary

RapidJSON is a leading high-performance JSON library for C++. Its built-in JSON Schema validation functionality makes it ideal for applications where data validation is critical. With zero-copy optimizations and support for both SAX and DOM approaches, it provides the flexibility to handle various use cases.