json

package module
v1.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 4, 2026 License: MIT Imports: 28 Imported by: 0

README ΒΆ

πŸš€ cybergodev/json - High-Performance Go JSON Processing Library

Go Version pkg.go.dev MIT license Performance Thread Safe

A high-performance, feature-rich Go JSON processing library with 100% encoding/json compatibility, providing powerful path operations, type safety, performance optimization, and rich advanced features.

πŸ“– δΈ­ζ–‡ζ–‡ζ‘£ - User guide

πŸ† Core Advantages

  • πŸ”„ Full Compatibility - 100% compatible with standard encoding/json, zero learning curve, drop-in replacement
  • 🎯 Powerful Paths - Support for complex path expressions, complete complex data operations in one line
  • πŸš€ High Performance - Smart caching, concurrent safety, memory optimization, production-ready performance
  • πŸ›‘οΈ Type Safety - Generic support, compile-time checking, intelligent type conversion
  • πŸ”§ Feature Rich - Batch operations, data validation, file operations, performance monitoring
  • πŸ—οΈ Production Ready - Thread-safe, error handling, security configuration, monitoring metrics
🎯 Use Cases
  • 🌐 API Data Processing - Fast extraction and transformation of complex response data
  • βš™οΈ Configuration Management - Dynamic configuration reading and batch updates
  • πŸ“Š Data Analysis - Statistics and analysis of large amounts of JSON data
  • πŸ”„ Microservice Communication - Data exchange and format conversion between services
  • πŸ“ Log Processing - Parsing and analysis of structured logs

πŸ“‹ Basic Path Syntax

Syntax Description Example Result
. Property access user.name Get user's name property
[n] Array index users[0] Get first user
[-n] Negative index users[-1] Get last user
[start:end:step] Array slice users[1:3] Get users at index 1-2
{field} Batch extract users{name} Extract all user names
{flat:field} Flatten extract users{flat:skills} Flatten extract all skills

πŸš€ Quick Start

Installation
go get github.com/cybergodev/json
Basic Usage
package main

import (
    "fmt"
    "github.com/cybergodev/json"
)

func main() {
    // 1. Full compatibility with standard library
    data := map[string]any{"name": "Alice", "age": 25}
    jsonBytes, err := json.Marshal(data)

    var result map[string]any
    json.Unmarshal(jsonBytes, &result)

    // 2. Powerful path operations (enhanced features)
    jsonStr := `{"user":{"profile":{"name":"Alice","age":25}}}`

    name, err := json.GetString(jsonStr, "user.profile.name")
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    fmt.Println(name) // "Alice"

    age, err := json.GetInt(jsonStr, "user.profile.age")
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    fmt.Println(age) // 25
}
Path Operations Example
// Complex JSON data
complexData := `{
  "users": [
    {"name": "Alice", "skills": ["Go", "Python"], "active": true},
    {"name": "Bob", "skills": ["Java", "React"], "active": false}
  ]
}`

// Get all usernames
names, err := json.Get(complexData, "users{name}")
if err != nil {
    fmt.Printf("Error: %v\n", err)
    return
}
// Result: ["Alice", "Bob"]

// Get all skills (flattened)
skills, err := json.Get(complexData, "users{flat:skills}")
if err != nil {
    fmt.Printf("Error: %v\n", err)
    return
}
// Result: ["Go", "Python", "Java", "React"]

// Batch get multiple values
paths := []string{"users[0].name", "users[1].name", "users{active}"}
results, err := json.GetMultiple(complexData, paths)
if err != nil {
    fmt.Printf("Error: %v\n", err)
    return
}

⚑ Core Features

Data Retrieval
// Basic retrieval
json.Get(data, "user.name")          // Get any type
json.GetString(data, "user.name")    // Get string
json.GetInt(data, "user.age")        // Get integer
json.GetFloat64(data, "user.score")  // Get float64
json.GetBool(data, "user.active")    // Get boolean
json.GetArray(data, "user.tags")     // Get array
json.GetObject(data, "user.profile") // Get object

// Type-safe retrieval
json.GetTyped[string](data, "user.name") // Generic type safety
json.GetTyped[[]User](data, "users")     // Custom types

// Retrieval with default values
json.GetWithDefault(data, "user.name", "Anonymous")
json.GetStringWithDefault(data, "user.name", "Anonymous")
json.GetIntWithDefault(data, "user.age", 0)
json.GetFloat64WithDefault(data, "user.score", 0.0)
json.GetBoolWithDefault(data, "user.active", false)
json.GetArrayWithDefault(data, "user.tags", []any{})
json.GetObjectWithDefault(data, "user.profile", map[string]any{})

// Batch retrieval
paths := []string{"user.name", "user.age", "user.email"}
results, err := json.GetMultiple(data, paths)
Data Modification
// Basic setting - returns modified data on success, original data on failure
data := `{"user":{"name":"Bob","age":25}}`
result, err := json.Set(data, "user.name", "Alice")
// result => {"user":{"name":"Alice","age":25}}

// Auto-create paths
data := `{}`
result, err := json.SetWithAdd(data, "user.name", "Alice")
// result => {"user":{"name":"Alice"}}

// Batch setting
updates := map[string]any{
    "user.name": "Bob",
    "user.age":  30,
    "user.active": true,
}
result, err := json.SetMultiple(data, updates)
result, err := json.SetMultipleWithAdd(data, updates) // With auto-create paths
// Same behavior: success = modified data, failure = original data
Data Deletion
json.Delete(data, "user.temp") // Delete field
json.DeleteWithCleanNull(data, "user.temp") // Delete and cleanup nulls
Data Iteration
// Basic iteration - read-only traversal
json.Foreach(data, func (key any, item *json.IterableValue) {
    name := item.GetString("name")
    fmt.Printf("Key: %v, Name: %s\n", key, name)
})

// Advanced iteration variants
json.ForeachNested(data, callback)                            // Recursively iterate all nested levels
json.ForeachWithPath(data, "data.users", callback)            // Iterate specific path
json.ForeachReturn(data, callback)                            // Modify and return modified JSON

// Iterate with control flow - supports early termination
json.ForeachWithPathAndControl(data, "data.users", func(key any, value any) json.IteratorControl {
    // Process each item
    if shouldStop {
        return json.IteratorBreak  // Stop iteration
    }
    return json.IteratorContinue  // Continue to next item
})

// Iterate with path information tracking
json.ForeachWithPathAndIterator(data, "data.users", func(key any, item *json.IterableValue, currentPath string) json.IteratorControl {
    name := item.GetString("name")
    fmt.Printf("User at %s: %s\n", currentPath, name)
    return json.IteratorContinue
})

// Complete Foreach functions list:
// - Foreach(data, callback) - Basic iteration
// - ForeachNested(data, callback) - Recursive iteration
// - ForeachWithPath(data, path, callback) - Path-specific iteration
// - ForeachWithPathAndControl(data, path, callback) - With flow control
// - ForeachWithPathAndIterator(data, path, callback) - With path info
// - ForeachReturn(data, callback) - Modify and return
JSON Encoding & Formatting
// Standard encoding (100% compatible with encoding/json)
bytes, err := json.Marshal(data)
err = json.Unmarshal(bytes, &target)
bytes, err := json.MarshalIndent(data, "", "  ")

// Advanced encoding with configuration
config := &json.EncodeConfig{
    Pretty:       true,
    SortKeys:     true,
    EscapeHTML:   false,
    MaxDepth:     10,  // Optional: maximum encoding depth (overriding default of 100)
}
jsonStr, err := json.Encode(data, config)           // Encode with custom config (config is optional, uses defaults if nil)
jsonStr, err := json.EncodePretty(data, config)     // Encode with pretty formatting

// Formatting operations
pretty, err := json.FormatPretty(jsonStr)
compact, err := json.FormatCompact(jsonStr)

// Print operations (direct output to stdout)
// Smart JSON detection: string/[]byte inputs are checked for validity first
json.Print(data)           // Print compact JSON to stdout
json.PrintPretty(data)     // Print pretty JSON to stdout

// Print examples
data := map[string]any{
    "monitoring": true,
    "database": map[string]any{
        "name": "myDb",
        "port": "5432",
        "ssl":  true,
    },
}

// Print Go value as compact JSON
json.Print(data)
// Output: {"monitoring":true,"database":{"name":"myDb","port":"5432","ssl":true}}

// Print Go value as pretty JSON
json.PrintPretty(data)
// Output:
// {
//   "database": {
//     "name": "myDb",
//     "port": "5432",
//     "ssl": true
//   },
//   "monitoring": true
// }

// Print JSON string directly (no double-encoding)
jsonStr := `{"name":"John","age":30}`
json.Print(jsonStr)
// Output: {"name":"John","age":30}

// Buffer operations (encoding/json compatible)
json.Compact(dst, src)
json.Indent(dst, src, prefix, indent)
json.HTMLEscape(dst, src)

// Advanced buffer operations with processor options
json.CompactBuffer(dst, src, opts)   // With custom processor options
json.IndentBuffer(dst, src, prefix, indent, opts)
json.HTMLEscapeBuffer(dst, src, opts)

// Advanced encoding methods
// Encode stream - encode multiple values as JSON array stream
users := []map[string]any{
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 30},
}
stream, err := json.EncodeStream(users, false)  // compact format

// Encode batch - encode multiple key-value pairs as JSON object
pairs := map[string]any{
    "user1": map[string]any{"name": "Alice", "age": 25},
    "user2": map[string]any{"name": "Bob", "age": 30},
}
batch, err := json.EncodeBatch(pairs, true)  // pretty format

// Encode fields - encode only specified fields from a struct
type User struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
}
user := User{Name: "Alice", Age: 25, Email: "[email protected]"}
fields, err := json.EncodeFields(user, []string{"name", "age"}, true)
// Output: {"name":"Alice","age":25}
File Operations
// Load and save JSON files
jsonStr, err := json.LoadFromFile("data.json")
err = json.SaveToFile("output.json", data, true) // pretty format

// Marshal/Unmarshal with files
err = json.MarshalToFile("user.json", user)
err = json.MarshalToFile("user_pretty.json", user, true)
err = json.UnmarshalFromFile("user.json", &loadedUser)

// Stream operations
data, err := processor.LoadFromReader(reader)
err = processor.SaveToWriter(writer, data, true)
Type Conversion & Utilities
// Safe type conversion
intVal, ok := json.ConvertToInt(value)
floatVal, ok := json.ConvertToFloat64(value)
boolVal, ok := json.ConvertToBool(value)
strVal := json.ConvertToString(value)

// Generic type conversion
result, ok := json.UnifiedTypeConversion[int](value)
result, err := json.TypeSafeConvert[string](value)

// JSON comparison and merging
equal, err := json.CompareJson(json1, json2)
merged, err := json.MergeJson(json1, json2)
copy, err := json.DeepCopy(data)
Processor Management
// Create processor with configuration
config := &json.Config{
    EnableCache:      true,
    MaxCacheSize:     5000,
    MaxJSONSize:      50 * 1024 * 1024,
    MaxConcurrency:   100,
    EnableValidation: true,
}
processor := json.New(config)
defer processor.Close()

// Processor operations
result, err := processor.Get(jsonStr, path)
stats := processor.GetStats()
health := processor.GetHealthStatus()
processor.ClearCache()

// Cache warmup
paths := []string{"user.name", "user.age", "user.profile"}
warmupResult, err := processor.WarmupCache(jsonStr, paths)

// Global processor management
json.SetGlobalProcessor(processor)
json.ShutdownGlobalProcessor()
Package-Level Convenience Methods

The library provides convenient package-level methods that use a default processor:

// Performance monitoring (uses default processor)
stats := json.GetStats()
fmt.Printf("Total operations: %d\n", stats.OperationCount)
fmt.Printf("Cache hit ratio: %.2f%%\n", stats.HitRatio*100)
fmt.Printf("Cache memory usage: %d bytes\n", stats.CacheMemory)

// Health monitoring
health := json.GetHealthStatus()
fmt.Printf("System healthy: %v\n", health.Healthy)

// Cache management
json.ClearCache()  // Clear all cached data

// Cache warmup - pre-load commonly used paths
paths := []string{"user.name", "user.age", "user.profile"}
warmupResult, err := json.WarmupCache(jsonStr, paths)

// Batch processing - execute multiple operations efficiently
operations := []json.BatchOperation{
    {Type: "get", Path: "user.name"},
    {Type: "set", Path: "user.age", Value: 25},
    {Type: "delete", Path: "user.temp"},
}
results, err := json.ProcessBatch(operations)
Complex Path Examples
complexData := `{
  "company": {
    "departments": [
      {
        "name": "Engineering",
        "teams": [
          {
            "name": "Backend",
            "members": [
              {"name": "Alice", "skills": ["Go", "Python"], "level": "Senior"},
              {"name": "Bob", "skills": ["Java", "Spring"], "level": "Mid"}
            ]
          }
        ]
      }
    ]
  }
}`

// Multi-level nested extraction
allMembers, err := json.Get(complexData, "company.departments{teams}{flat:members}")
// Result: [Alice's data, Bob's data]

// Extract specific fields
allNames, err := json.Get(complexData, "company.departments{teams}{flat:members}{name}")
// Result: ["Alice", "Bob"]

// Flatten skills extraction
allSkills, err := json.Get(complexData, "company.departments{teams}{flat:members}{flat:skills}")
// Result: ["Go", "Python", "Java", "Spring"]
Array Operations
arrayData := `{
  "numbers": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  "users": [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 30}
  ]
}`

// Array indexing and slicing
first, err := json.GetInt(arrayData, "numbers[0]")           // 1
last, err := json.GetInt(arrayData, "numbers[-1]")           // 10 (negative index)
slice, err := json.Get(arrayData, "numbers[1:4]")            // [2, 3, 4]
everyOther, err := json.Get(arrayData, "numbers[::2]")       // [1, 3, 5, 7, 9]
reverseEveryOther, err := json.Get(arrayData, "numbers[::-2]")  // [10, 8, 6, 4, 2]

// Nested array access
ages, err := json.Get(arrayData, "users{age}") // [25, 30]

πŸ”§ Configuration Options

Processor Configuration

The json.New() function now supports optional configuration parameters:

// 1. No parameters - uses default configuration
processor1 := json.New()
defer processor1.Close()

// 2. Custom configuration
customConfig := &json.Config{
    // Cache settings
    EnableCache:      true,             // Enable cache
    MaxCacheSize:     128,              // Cache entry count (default)
    CacheTTL:         5 * time.Minute,  // Cache expiration time (default)

    // Size limits
    MaxJSONSize:      100 * 1024 * 1024, // 100MB JSON size limit (default)
    MaxPathDepth:     50,                // Path depth limit (default)
    MaxBatchSize:     2000,              // Batch operation size limit

    // Concurrency settings
    MaxConcurrency:   50,   // Maximum concurrency (default)
    ParallelThreshold: 10,   // Parallel processing threshold (default)

    // Processing options
    EnableValidation: true,  // Enable validation
    StrictMode:       false, // Non-strict mode
    CreatePaths:      true,  // Auto-create paths
    CleanupNulls:     true,  // Cleanup null values
}

processor2 := json.New(customConfig)
defer processor2.Close()

// 3. Predefined configurations
// HighSecurityConfig: For processing untrusted JSON with strict validation limits
secureProcessor := json.New(json.HighSecurityConfig())
defer secureProcessor.Close()

// LargeDataConfig: For handling large JSON files with optimized performance
largeDataProcessor := json.New(json.LargeDataConfig())
defer largeDataProcessor.Close()
Operation Options
opts := &json.ProcessorOptions{
    CreatePaths:     true,  // Auto-create paths
    CleanupNulls:    true,  // Cleanup null values
    CompactArrays:   true,  // Compact arrays
    ContinueOnError: false, // Continue on error
    MaxDepth:        50,    // Maximum depth
}

result, err := json.Get(data, "path", opts)
Performance Monitoring
processor := json.New(json.DefaultConfig())
defer processor.Close()

// Get statistics after operations
stats := processor.GetStats()
fmt.Printf("Total operations: %d\n", stats.OperationCount)
fmt.Printf("Cache hit rate: %.2f%%\n", stats.HitRatio*100)
fmt.Printf("Cache memory usage: %d bytes\n", stats.CacheMemory)

// Get health status
health := processor.GetHealthStatus()
fmt.Printf("System health: %v\n", health.Healthy)

πŸ“ File Operations

Basic File Operations
// Load JSON from file
data, err := json.LoadFromFile("example.json")

// Save to file (pretty format)
err = json.SaveToFile("output_pretty.json", data, true)

// Save to file (compact format)
err = json.SaveToFile("output.json", data, false)

// Load from Reader (using processor)
processor := json.New()
defer processor.Close()

file, err := os.Open("large_data.json")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

data, err := processor.LoadFromReader(file)

// Save to Writer (using processor)
var buffer bytes.Buffer
err = processor.SaveToWriter(&buffer, data, true)
Marshal/Unmarshal File Operations
// Marshal data to file (compact format by default)
user := map[string]any{
    "name": "Alice",
    "age":  30,
    "email": "[email protected]",
}
err := json.MarshalToFile("user.json", user)

// Marshal data to file (pretty format)
err = json.MarshalToFile("user_pretty.json", user, true)

// Unmarshal data from file
var loadedUser map[string]any
err = json.UnmarshalFromFile("user.json", &loadedUser)

// Works with structs too
type User struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
}

var person User
err = json.UnmarshalFromFile("user.json", &person)

// Using processor for advanced options
processor := json.New()
defer processor.Close()

err = processor.MarshalToFile("advanced.json", user, true)
err = processor.UnmarshalFromFile("advanced.json", &loadedUser, opts...)
Batch File Processing
configFiles := []string{
    "database.json",
    "cache.json",
    "logging.json",
}

allConfigs := make(map[string]any)

for _, filename := range configFiles {
    config, err := json.LoadFromFile(filename)
    if err != nil {
        log.Printf("Loading %s failed: %v", filename, err)
        continue
    }

    configName := strings.TrimSuffix(filename, ".json")
    allConfigs[configName] = config
}

// Save merged configuration
err = json.SaveToFile("merged_config.json", allConfigs, true)
if err != nil {
    log.Printf("Saving merged config failed: %v", err)
    return
}

Security Configuration
// Security configuration
secureConfig := &json.Config{
    MaxJSONSize:              10 * 1024 * 1024, // 10MB JSON size limit
    MaxPathDepth:             50,                // Path depth limit
    MaxNestingDepthSecurity:  100,               // Object nesting depth limit
    MaxArrayElements:         10000,             // Array element count limit
    MaxObjectKeys:            1000,              // Object key count limit
    ValidateInput:            true,              // Input validation
    EnableValidation:         true,              // Enable validation
    StrictMode:               true,              // Strict mode
}

processor := json.New(secureConfig)
defer processor.Close()

🎯 Use Cases

Example - API Response Processing
// Typical REST API response
apiResponse := `{
    "status": "success",
    "code": 200,
    "data": {
        "users": [
            {
                "id": 1,
                "profile": {
                    "name": "Alice Johnson",
                    "email": "[email protected]"
                },
                "permissions": ["read", "write", "admin"],
                "metadata": {
                    "created_at": "2023-01-15T10:30:00Z",
                    "tags": ["premium", "verified"]
                }
            }
        ],
        "pagination": {
            "page": 1,
            "total": 25
        }
    }
}`

// Quick extraction of key information
status, err := json.GetString(apiResponse, "status")
if err != nil {
    fmt.Printf("Error: %v\n", err)
    return
}
// Result: success

code, err := json.GetInt(apiResponse, "code")
if err != nil {
    fmt.Printf("Error: %v\n", err)
    return
}
// Result: 200

// Get pagination information
totalUsers, err := json.GetInt(apiResponse, "data.pagination.total")
if err != nil {
    fmt.Printf("Error: %v\n", err)
    return
}
// Result: 25

currentPage, err := json.GetInt(apiResponse, "data.pagination.page")
if err != nil {
    fmt.Printf("Error: %v\n", err)
    return
}
// Result: 1

// Batch extract user information
userNames, err := json.Get(apiResponse, "data.users.profile.name")
if err != nil {
    fmt.Printf("Error: %v\n", err)
    return
}
// Result: ["Alice Johnson"]

userEmails, err := json.Get(apiResponse, "data.users.profile.email")
if err != nil {
    fmt.Printf("Error: %v\n", err)
    return
}
// Result: ["[email protected]"]

// Flatten extract all permissions
allPermissions, err := json.Get(apiResponse, "data.users{flat:permissions}")
if err != nil {
    fmt.Printf("Error: %v\n", err)
    return
}
// Result: ["read", "write", "admin"]
Example - Configuration File Management
// Multi-environment configuration file
configJSON := `{
    "app": {
        "name": "MyApplication",
        "version": "1.2.3"
    },
    "environments": {
        "development": {
            "database": {
                "host": "localhost",
                "port": 5432,
                "name": "myapp_dev"
            },
            "cache": {
                "enabled": true,
                "host": "localhost",
                "port": 6379
            }
        },
        "production": {
            "database": {
                "host": "prod-db.example.com",
                "port": 5432,
                "name": "myapp_prod"
            },
            "cache": {
                "enabled": true,
                "host": "prod-cache.example.com",
                "port": 6379
            }
        }
    }
}`

// Type-safe configuration retrieval
dbHost := json.GetStringWithDefault(configJSON, "environments.production.database.host", "localhost")
dbPort := json.GetIntWithDefault(configJSON, "environments.production.database.port", 5432)
cacheEnabled := json.GetBoolWithDefault(configJSON, "environments.production.cache.enabled", false)

fmt.Printf("Production database: %s:%d\n", dbHost, dbPort)
fmt.Printf("Cache enabled: %v\n", cacheEnabled)

// Dynamic configuration updates
updates := map[string]any{
    "app.version": "1.2.4",
    "environments.production.cache.ttl": 10800, // 3 hours
}

newConfig, err := json.SetMultiple(configJSON, updates)
if err != nil {
    fmt.Printf("Error updating config: %v\n", err)
    return
}
Example - Data Analysis Processing
// Log and monitoring data
analyticsData := `{
    "events": [
        {
            "type": "request",
            "user_id": "user_123",
            "endpoint": "/api/users",
            "status_code": 200,
            "response_time": 45
        },
        {
            "type": "error",
            "user_id": "user_456",
            "endpoint": "/api/orders",
            "status_code": 500,
            "response_time": 5000
        }
    ]
}`

// Extract all event types
eventTypes, err := json.Get(analyticsData, "events.type")
if err != nil {
    fmt.Printf("Error: %v\n", err)
    return
}
// Result: ["request", "error"]

// Extract all status codes
statusCodes, err := json.Get(analyticsData, "events.status_code")
if err != nil {
    fmt.Printf("Error: %v\n", err)
    return
}
// Result: [200, 500]

// Extract all response times
responseTimes, err := json.GetTyped[[]int](analyticsData, "events.response_time")
if err != nil {
    fmt.Printf("Error: %v\n", err)
    return
}
// Result: [45, 5000]

// Calculate average response time
times := responseTimes
var total float64
for _, t := range times {
    total += t
}

avgTime := total / float64(len(times))
fmt.Printf("Average response time: %.2f ms\n", avgTime)

Set Operations - Data Safety Guarantee

All Set operations follow a safe-by-default pattern that ensures your data is never corrupted:

// βœ… Success: Returns modified data
result, err := json.Set(data, "user.name", "Alice")
if err == nil {
    // result contains successfully modified JSON
    fmt.Println("Data updated:", result)
}

// ❌ Failure: Returns original unmodified data
result, err := json.Set(data, "invalid[path", "value")
if err != nil {
    // result still contains valid original data
    // Your original data is NEVER corrupted
    fmt.Printf("Set failed: %v\n", err)
    fmt.Println("Original data preserved:", result)
}

Key Benefits:

  • πŸ”’ Data Integrity: Original data never corrupted on error
  • βœ… Safe Fallback: Always have valid JSON to work with
  • 🎯 Predictable: Consistent behavior across all operations

πŸ“¦ Advanced Features

JSONL (JSON Lines) Support

The library provides comprehensive support for JSON Lines format, commonly used for logs, data pipelines, and streaming data:

// Parse JSONL data
jsonlData := `{"name":"Alice","age":25}
{"name":"Bob","age":30}
{"name":"Carol","age":28}`

// Parse into slice
results, err := json.ParseJSONL([]byte(jsonlData))

// Stream processing for large files
processor := json.NewJSONLProcessor(reader)
err := processor.StreamLines(func(lineNum int, data any) bool {
    fmt.Printf("Line %d: %v\n", lineNum, data)
    return true // continue processing
})

// Parallel processing for CPU-bound operations
err := processor.StreamLinesParallel(func(lineNum int, data any) error {
    // Process each line in parallel
    return nil
}, 4) // 4 workers

// Type-safe streaming with generics
type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}
users, err := json.StreamLinesInto[User](reader, func(lineNum int, user User) error {
    fmt.Printf("User: %s, Age: %d\n", user.Name, user.Age)
    return nil
})

// Write JSONL output
writer := json.NewJSONLWriter(outputWriter)
writer.Write(map[string]any{"event": "login", "user": "alice"})
writer.Write(map[string]any{"event": "logout", "user": "bob"})

// Convert slice to JSONL
data := []any{
    map[string]any{"id": 1, "name": "Alice"},
    map[string]any{"id": 2, "name": "Bob"},
}
jsonlBytes, err := json.ToJSONL(data)
Streaming Processing

For large JSON files, use streaming processors to avoid loading everything into memory:

// Create streaming processor
processor := json.NewStreamingProcessor(reader, 64*1024) // 64KB buffer

// Stream array elements one at a time
err := processor.StreamArray(func(index int, item any) bool {
    fmt.Printf("Item %d: %v\n", index, item)
    return true // continue
})

// Stream object key-value pairs
err := processor.StreamObject(func(key string, value any) bool {
    fmt.Printf("Key: %s, Value: %v\n", key, value)
    return true
})

// Chunked processing for batch operations
err := processor.StreamArrayChunked(100, func(chunk []any) error {
    // Process 100 items at a time
    return nil
})

// Stream transformations
filtered, err := json.StreamArrayFilter(reader, func(item any) bool {
    return item.(map[string]any)["active"] == true
})

transformed, err := json.StreamArrayMap(reader, func(item any) any {
    item.(map[string]any)["processed"] = true
    return item
})

// Memory-efficient array counting
count, err := json.StreamArrayCount(reader)

// Get first matching element (stops early)
first, found, err := json.StreamArrayFirst(reader, func(item any) bool {
    return item.(map[string]any)["priority"] == "high"
})

// Pagination support
page2, err := json.StreamArraySkip(reader, 10)  // Skip first 10
page, err := json.StreamArrayTake(reader, 10)   // Take first 10
Lazy JSON Parsing

Parse JSON on-demand for improved performance when only accessing specific paths:

// Create lazy parser - parsing happens on first access
lazy := json.NewLazyJSON(jsonBytes)

// Parse only when Get is called
value, err := lazy.Get("user.profile.name")

// Check if already parsed
if lazy.IsParsed() {
    data := lazy.Parsed()
}

// Get parsing error (triggers parsing if not done)
if err := lazy.Error(); err != nil {
    log.Printf("Parse error: %v", err)
}

// Access raw bytes without parsing
rawBytes := lazy.Raw()
Large File Processing

Process very large JSON files efficiently:

// Configure for large files
config := json.LargeFileConfig{
    ChunkSize:       1024 * 1024,       // 1MB chunks
    MaxMemory:       100 * 1024 * 1024, // 100MB max
    BufferSize:      64 * 1024,         // 64KB buffer
    SamplingEnabled: true,
    SampleSize:      1000,
}

processor := json.NewLargeFileProcessor(config)

// Process file element by element
err := processor.ProcessFile("large.json", func(item any) error {
    // Process each item without loading entire file
    return nil
})

// Process in chunks for batch operations
err := processor.ProcessFileChunked("large.json", 100, func(chunk []any) error {
    // Process 100 items at a time
    return nil
})

// Chunked reader for custom processing
reader := json.NewChunkedReader(file, 1024*1024)
err := reader.ReadArray(func(item any) bool {
    // Process each item
    return true
})
NDJSON Processing

Process newline-delimited JSON files efficiently:

processor := json.NewNDJSONProcessor(64 * 1024) // 64KB buffer

// Process file line by line
err := processor.ProcessFile("logs.ndjson", func(lineNum int, obj map[string]any) error {
    fmt.Printf("Line %d: %v\n", lineNum, obj)
    return nil
})

// Process from reader
err := processor.ProcessReader(reader, func(lineNum int, obj map[string]any) error {
    // Process each JSON object
    return nil
})

πŸ’‘ Examples & Resources

πŸ“ Example Code
πŸ“– Additional Resources

🀝 Contributing

Contributions, issue reports, and suggestions are welcome!

πŸ“„ License

MIT License - See LICENSE file for details.


Crafted with care for the Go community ❀️ | If this project helps you, please give it a ⭐️ Star!

Documentation ΒΆ

Overview ΒΆ

Package json provides a high-performance, thread-safe JSON processing library with 100% encoding/json compatibility and advanced path operations.

The package uses an internal package for implementation details:

  • internal: Private implementation including path parsing, navigation, extraction, caching, array utilities, security helpers, and encoding utilities

Most users can simply import the root package:

import "github.com/cybergodev/json"

Basic Usage ΒΆ

Simple operations (100% compatible with encoding/json):

data, err := json.Marshal(value)
err = json.Unmarshal(data, &target)

Advanced path operations:

value, err := json.Get(`{"user":{"name":"John"}}`, "user.name")
result, err := json.Set(`{"user":{}}`, "user.age", 30)

Type-safe operations:

name, err := json.GetString(jsonStr, "user.name")
age, err := json.GetInt(jsonStr, "user.age")

Advanced processor for complex operations:

processor := json.New() // Use default config
defer processor.Close()
value, err := processor.Get(jsonStr, "complex.path[0].field")

Configuration ΒΆ

Use NewWithConfig for custom configuration:

cfg := json.NewConfig()
cfg.EnableCache = true
processor := json.NewWithConfig(cfg)
defer processor.Close()

Key Features ΒΆ

  • 100% encoding/json compatibility - drop-in replacement
  • High-performance path operations with smart caching
  • Thread-safe concurrent operations
  • Type-safe generic operations with Go 1.22+ features
  • Memory-efficient resource pooling
  • Production-ready error handling and validation

Package Structure ΒΆ

The package is organized with all public API in the root package:

  • Core types: Processor, Config, ProcessorOptions, EncodeConfig
  • Path types: PathSegment, PathInfo, PropertyAccessResult
  • Error types: JsonsError, various error constructors
  • Encoding types: Number, NumberPreservingDecoder, CustomEncoder

Implementation details are in the internal/ package:

  • Path parsing and navigation utilities
  • Extraction and segment handling
  • Cache and array utilities
  • Security and encoding helpers

Core Types Organization ΒΆ

Core types are organized in the following files:

  • types.go: All type definitions (Config, ProcessorOptions, Stats, PathSegment, etc.)
  • processor.go: Processor struct and all methods
  • ops.go: Internal operation implementations
  • path.go: Path parsing and navigation
  • encoding.go: JSON encoding/decoding
  • api.go: Package-level API functions
  • file.go: File operations
  • iterator.go: Iteration utilities
  • recursive.go: Recursive processing

Package json provides a high-performance, thread-safe JSON processing library with 100% encoding/json compatibility and advanced path operations.

Key Features:

  • 100% encoding/json compatibility - drop-in replacement
  • High-performance path operations with smart caching
  • Thread-safe concurrent operations
  • Type-safe generic operations with Go 1.22+ features
  • Memory-efficient resource pooling
  • Production-ready error handling and validation

Basic Usage:

// Simple operations (100% compatible with encoding/json)
data, err := json.Marshal(value)
err = json.Unmarshal(data, &target)

// Advanced path operations
value, err := json.Get(`{"user":{"name":"John"}}`, "user.name")
result, err := json.Set(`{"user":{}}`, "user.age", 30)

// Type-safe operations
name, err := json.GetString(jsonStr, "user.name")
age, err := json.GetInt(jsonStr, "user.age")

// Advanced processor for complex operations
processor := json.New() // Use default config
defer processor.Close()
value, err := processor.Get(jsonStr, "complex.path[0].field")

Index ΒΆ

Constants ΒΆ

View Source
const (
	// Buffer and Pool Sizes - Optimized for production workloads
	DefaultBufferSize        = 1024
	MaxPoolBufferSize        = 32768 // 32KB max for better buffer reuse
	MinPoolBufferSize        = 256   // 256B min for efficiency
	DefaultPathSegmentCap    = 8
	MaxPathSegmentCap        = 32 // Reduced from 128
	DefaultStringBuilderSize = 256

	// Cache Sizes - Balanced for performance and memory
	DefaultCacheSize     = 128
	MaxCacheEntries      = 512
	CacheCleanupKeepSize = 256

	// Operation Limits - Secure defaults with reasonable headroom
	// InvalidArrayIndex is a sentinel value indicating an invalid or out-of-bounds array index
	InvalidArrayIndex        = -999999
	DefaultMaxJSONSize       = 100 * 1024 * 1024 // 100MB
	DefaultMaxSecuritySize   = 10 * 1024 * 1024
	DefaultMaxNestingDepth   = 200
	DefaultMaxObjectKeys     = 100000
	DefaultMaxArrayElements  = 100000
	DefaultMaxPathDepth      = 50
	DefaultMaxBatchSize      = 2000
	DefaultMaxConcurrency    = 50
	DefaultParallelThreshold = 10

	// Timing and Intervals - Optimized for responsiveness
	MemoryPressureCheckInterval = 30 * time.Second
	PoolResetInterval           = 60 * time.Second
	PoolResetIntervalPressure   = 30 * time.Second
	CacheCleanupInterval        = 30 * time.Second
	DeadlockCheckInterval       = 30 * time.Second
	DeadlockThreshold           = 30 * time.Second
	SlowOperationThreshold      = 100 * time.Millisecond

	// Retry and Timeout - Production-ready settings
	MaxRetries              = 3
	BaseRetryDelay          = 10 * time.Millisecond
	DefaultOperationTimeout = 30 * time.Second
	AcquireSlotRetryDelay   = 1 * time.Millisecond

	// Path Validation - Secure but flexible
	// Note: MaxPathLength (5000) is also defined in internal/constants.go for internal use
	// Both definitions must be kept in sync
	MaxPathLength    = 5000
	MaxSegmentLength = 1024

	// Cache TTL
	DefaultCacheTTL = 5 * time.Minute

	// JSON processing thresholds
	SmallJSONThreshold  = 256  // Threshold for lightweight JSON normalization
	MediumJSONThreshold = 1024 // Threshold for full JSON normalization

	// Cache key constants - OPTIMIZED: Increased limits for better cache hit rate
	CacheKeyHashLength   = 32      // Length for cache key hash
	SmallJSONCacheLimit  = 2048    // Limit for caching small JSON strings (fast path)
	MediumJSONCacheLimit = 51200   // Limit for caching medium JSON strings (50KB)
	LargeJSONCacheLimit  = 1048576 // Limit for caching large JSON strings (1MB) - OPTIMIZED: increased for better performance
	EstimatedKeyOverhead = 32      // Estimated overhead for cache key generation
	LargeJSONKeyOverhead = 64      // Overhead for large JSON cache keys
	MaxCacheKeyLength    = 500     // Maximum allowed cache key length

	// Validation constants
	ValidationBOMPrefix = "\uFEFF" // UTF-8 BOM prefix to detect and remove
)

Configuration constants with optimized defaults for production workloads.

View Source
const (
	ErrCodeInvalidJSON       = "ERR_INVALID_JSON"
	ErrCodePathNotFound      = "ERR_PATH_NOT_FOUND"
	ErrCodeTypeMismatch      = "ERR_TYPE_MISMATCH"
	ErrCodeSizeLimit         = "ERR_SIZE_LIMIT"
	ErrCodeDepthLimit        = "ERR_DEPTH_LIMIT"
	ErrCodeSecurityViolation = "ERR_SECURITY_VIOLATION"
	ErrCodeOperationFailed   = "ERR_OPERATION_FAILED"
	ErrCodeTimeout           = "ERR_TIMEOUT"
	ErrCodeConcurrencyLimit  = "ERR_CONCURRENCY_LIMIT"
	ErrCodeProcessorClosed   = "ERR_PROCESSOR_CLOSED"
	ErrCodeRateLimit         = "ERR_RATE_LIMIT"
)

Error codes for machine-readable error identification.

Variables ΒΆ

View Source
var (
	ErrInvalidJSON     = errors.New("invalid JSON format")
	ErrPathNotFound    = errors.New("path not found")
	ErrTypeMismatch    = errors.New("type mismatch")
	ErrOperationFailed = errors.New("operation failed")
	ErrInvalidPath     = errors.New("invalid path format")
	ErrProcessorClosed = errors.New("processor is closed")

	// Limit-related errors.
	ErrSizeLimit        = errors.New("size limit exceeded")
	ErrDepthLimit       = errors.New("depth limit exceeded")
	ErrConcurrencyLimit = errors.New("concurrency limit exceeded")

	// Security and validation errors.
	ErrSecurityViolation = errors.New("security violation detected")
	ErrUnsupportedPath   = errors.New("unsupported path operation")

	// Resource and performance errors.
	ErrCacheFull         = errors.New("cache is full")
	ErrCacheDisabled     = errors.New("cache is disabled")
	ErrOperationTimeout  = errors.New("operation timeout")
	ErrResourceExhausted = errors.New("system resources exhausted")

	// Control flow errors (internal use).
	ErrIteratorControl = errors.New("iterator control signal")
)

Primary errors for common cases.

View Source
var DeletedMarker = &struct{}{} // deleted marker - empty struct for pointer identity

DeletedMarker is a special sentinel value used to mark array elements for deletion. It is compared by pointer identity (using ==). SECURITY: This is an unexported struct pointer to prevent external modification. The zero-size struct{}{} is used because we only need unique pointer identity.

Functions ΒΆ

func ClampIndex ΒΆ

func ClampIndex(index, length int) int

ClampIndex clamps an index to valid bounds for an array

func ClearCache ΒΆ added in v1.1.0

func ClearCache()

ClearCache clears the processor's internal cache.

func ClearKeyInternCache ΒΆ added in v1.2.0

func ClearKeyInternCache()

ClearKeyInternCache clears the key intern cache

func Compact ΒΆ

func Compact(dst *bytes.Buffer, src []byte) error

Compact appends to dst the JSON-encoded src with insignificant space characters elided. This function is 100% compatible with encoding/json.Compact.

func CompactBuffer ΒΆ added in v1.1.0

func CompactBuffer(dst *bytes.Buffer, src []byte, opts ...*ProcessorOptions) error

CompactBuffer is an alias for Compact for buffer operations

func CompactString ΒΆ added in v1.2.2

func CompactString(jsonStr string, opts ...*ProcessorOptions) (string, error)

CompactString removes whitespace from JSON string. This is the recommended function name for consistency with Processor.Compact.

func CompareJson ΒΆ

func CompareJson(json1, json2 string) (bool, error)

CompareJson compares two JSON strings for equality

func ConvertFromScientific ΒΆ

func ConvertFromScientific(s string) (string, error)

ConvertFromScientific converts a scientific notation string to regular number format

func ConvertToBool ΒΆ added in v1.0.4

func ConvertToBool(value any) (bool, bool)

ConvertToBool converts any value to bool. String conversion supports both standard formats and user-friendly formats: Standard: "1", "t", "T", "TRUE", "true", "True", "0", "f", "F", "FALSE", "false", "False" Extended: "yes", "on" -> true, "no", "off", "" -> false REFACTORED: Uses internal core function to reduce code duplication

func ConvertToFloat64 ΒΆ added in v1.0.4

func ConvertToFloat64(value any) (float64, bool)

ConvertToFloat64 converts any value to float64 REFACTORED: Uses internal core function to reduce code duplication

func ConvertToInt ΒΆ added in v1.0.4

func ConvertToInt(value any) (int, bool)

ConvertToInt converts any value to int with comprehensive type support REFACTORED: Uses internal core function to reduce code duplication

func ConvertToInt64 ΒΆ added in v1.0.4

func ConvertToInt64(value any) (int64, bool)

ConvertToInt64 converts any value to int64 REFACTORED: Uses internal core function to reduce code duplication

func ConvertToString ΒΆ added in v1.0.4

func ConvertToString(value any) string

ConvertToString converts any value to string (for backward compatibility)

func ConvertToUint64 ΒΆ added in v1.0.4

func ConvertToUint64(value any) (uint64, bool)

ConvertToUint64 converts any value to uint64 REFACTORED: Uses internal core function to reduce code duplication

func CreateEmptyContainer ΒΆ

func CreateEmptyContainer(containerType string) any

CreateEmptyContainer creates an empty container of the specified type

func DeepCopy ΒΆ

func DeepCopy(data any) (any, error)

DeepCopy creates a deep copy of JSON-compatible data Uses direct recursive copying for better performance (avoids marshal/unmarshal overhead) SECURITY: Added depth limit to prevent stack overflow

func Delete ΒΆ

func Delete(jsonStr, path string, opts ...*ProcessorOptions) (string, error)

Delete deletes a value from JSON at the specified path

func DeleteWithCleanNull ΒΆ

func DeleteWithCleanNull(jsonStr, path string, opts ...*ProcessorOptions) (string, error)

DeleteWithCleanNull removes a value from JSON and cleans up null values

func Encode ΒΆ

func Encode(value any, config ...*EncodeConfig) (string, error)

Encode converts any Go value to JSON string

func EncodeBatch ΒΆ added in v1.1.0

func EncodeBatch(pairs map[string]any, pretty bool, opts ...*ProcessorOptions) (string, error)

EncodeBatch encodes multiple key-value pairs as a JSON object.

func EncodeFields ΒΆ added in v1.1.0

func EncodeFields(value any, fields []string, pretty bool, opts ...*ProcessorOptions) (string, error)

EncodeFields encodes specific fields from a struct or map.

func EncodePretty ΒΆ

func EncodePretty(value any, config ...*EncodeConfig) (string, error)

EncodePretty converts any Go value to pretty-formatted JSON string

func EncodeStream ΒΆ added in v1.1.0

func EncodeStream(values any, pretty bool, opts ...*ProcessorOptions) (string, error)

EncodeStream encodes multiple values as a JSON stream.

func EncodeWithOptions ΒΆ added in v1.2.2

func EncodeWithOptions(value any, config *EncodeConfig, opts ...*ProcessorOptions) (string, error)

EncodeWithOptions converts any Go value to JSON string with processor options. This allows passing both EncodeConfig and ProcessorOptions in a single call.

func EscapeJSONPointer ΒΆ

func EscapeJSONPointer(s string) string

EscapeJSONPointer escapes special characters for JSON Pointer

func EstimateArraySize ΒΆ added in v1.2.0

func EstimateArraySize(jsonBytes []byte) int

EstimateArraySize estimates the number of elements in a JSON array from raw bytes PERFORMANCE: Pre-sizing arrays reduces reallocation overhead

func EstimateMapSize ΒΆ added in v1.2.0

func EstimateMapSize(jsonBytes []byte) int

EstimateMapSize estimates the number of keys in a JSON object from raw bytes PERFORMANCE: Pre-sizing maps reduces reallocation overhead

func FastToBool ΒΆ added in v1.2.0

func FastToBool(value any) (bool, bool)

FastToBool converts any value to bool using optimized type switch PERFORMANCE: Avoids reflection for common types

func FastToFloat64 ΒΆ added in v1.2.0

func FastToFloat64(value any) (float64, bool)

FastToFloat64 converts any value to float64 using optimized type switch PERFORMANCE: Avoids reflection for common types

func FastToInt ΒΆ added in v1.2.0

func FastToInt(value any) (int, bool)

FastToInt converts any value to int using optimized type switch PERFORMANCE: Avoids reflection for common types

func FastToString ΒΆ added in v1.2.0

func FastToString(value any) (string, bool)

FastToString converts any value to string using optimized type switch PERFORMANCE: Avoids reflection for common types

func FastTypeSwitch ΒΆ added in v1.2.0

func FastTypeSwitch[T any](value any) (T, bool)

FastTypeSwitch converts a value to a specific type using optimized type switches PERFORMANCE: Single type switch instead of multiple type assertions

func Foreach ΒΆ

func Foreach(jsonStr string, fn func(key any, item *IterableValue))

Foreach iterates over JSON arrays or objects with simplified signature (for test compatibility)

func ForeachNested ΒΆ

func ForeachNested(jsonStr string, fn func(key any, item *IterableValue))

ForeachNested iterates over nested JSON structures

func ForeachReturn ΒΆ

func ForeachReturn(jsonStr string, fn func(key any, item *IterableValue)) (string, error)

ForeachReturn is a variant that returns error (for compatibility with test expectations)

func ForeachWithPath ΒΆ

func ForeachWithPath(jsonStr, path string, fn func(key any, item *IterableValue)) error

ForeachWithPath iterates over JSON arrays or objects with simplified signature (for test compatibility)

func ForeachWithPathAndControl ΒΆ added in v1.0.8

func ForeachWithPathAndControl(jsonStr, path string, fn func(key any, value any) IteratorControl) error

ForeachWithPathAndControl iterates over JSON arrays or objects and applies a function This is the 3-parameter version used by most code

func FormatCompact deprecated

func FormatCompact(jsonStr string, opts ...*ProcessorOptions) (string, error)

FormatCompact removes whitespace from JSON string.

Deprecated: Use CompactString for consistency with Processor.Compact.

func FormatNumber ΒΆ

func FormatNumber(value any) string

FormatNumber formats a number value as a string

func FormatPretty ΒΆ

func FormatPretty(jsonStr string, opts ...*ProcessorOptions) (string, error)

FormatPretty formats JSON string with pretty indentation.

func Get ΒΆ

func Get(jsonStr, path string, opts ...*ProcessorOptions) (any, error)

Get retrieves a value from JSON at the specified path

func GetArray ΒΆ

func GetArray(jsonStr, path string, opts ...*ProcessorOptions) ([]any, error)

GetArray retrieves an array value from JSON at the specified path

func GetArrayWithDefault ΒΆ

func GetArrayWithDefault(jsonStr, path string, defaultValue []any, opts ...*ProcessorOptions) []any

GetArrayWithDefault retrieves an array value from JSON at the specified path with a default fallback

func GetBool ΒΆ

func GetBool(jsonStr, path string, opts ...*ProcessorOptions) (bool, error)

GetBool retrieves a bool value from JSON at the specified path

func GetBoolWithDefault ΒΆ

func GetBoolWithDefault(jsonStr, path string, defaultValue bool, opts ...*ProcessorOptions) bool

GetBoolWithDefault retrieves a bool value from JSON at the specified path with a default fallback

func GetContainerSize ΒΆ

func GetContainerSize(data any) int

GetContainerSize returns the size of a container

func GetEncodeBuffer ΒΆ added in v1.2.0

func GetEncodeBuffer() []byte

GetEncodeBuffer gets a buffer for encoding operations

func GetErrorSuggestion ΒΆ added in v1.0.10

func GetErrorSuggestion(err error) string

GetErrorSuggestion provides suggestions for common errors

func GetFloat64 ΒΆ

func GetFloat64(jsonStr, path string, opts ...*ProcessorOptions) (float64, error)

GetFloat64 retrieves a float64 value from JSON at the specified path

func GetFloat64WithDefault ΒΆ

func GetFloat64WithDefault(jsonStr, path string, defaultValue float64, opts ...*ProcessorOptions) float64

GetFloat64WithDefault retrieves a float64 value from JSON at the specified path with a default fallback

func GetInt ΒΆ

func GetInt(jsonStr, path string, opts ...*ProcessorOptions) (int, error)

GetInt retrieves an int value from JSON at the specified path

func GetIntWithDefault ΒΆ

func GetIntWithDefault(jsonStr, path string, defaultValue int, opts ...*ProcessorOptions) int

GetIntWithDefault retrieves an int value from JSON at the specified path with a default fallback

func GetMultiple ΒΆ

func GetMultiple(jsonStr string, paths []string, opts ...*ProcessorOptions) (map[string]any, error)

GetMultiple retrieves multiple values from JSON at the specified paths

func GetObject ΒΆ

func GetObject(jsonStr, path string, opts ...*ProcessorOptions) (map[string]any, error)

GetObject retrieves an object value from JSON at the specified path

func GetObjectWithDefault ΒΆ

func GetObjectWithDefault(jsonStr, path string, defaultValue map[string]any, opts ...*ProcessorOptions) map[string]any

GetObjectWithDefault retrieves an object value from JSON at the specified path with a default fallback

func GetResultBuffer ΒΆ added in v1.2.0

func GetResultBuffer() *[]byte

GetResultBuffer gets a buffer for result marshaling

func GetString ΒΆ

func GetString(jsonStr, path string, opts ...*ProcessorOptions) (string, error)

GetString retrieves a string value from JSON at the specified path

func GetStringWithDefault ΒΆ

func GetStringWithDefault(jsonStr, path, defaultValue string, opts ...*ProcessorOptions) string

GetStringWithDefault retrieves a string value from JSON at the specified path with a default fallback

func GetTyped ΒΆ

func GetTyped[T any](jsonStr, path string, opts ...*ProcessorOptions) (T, error)

GetTyped retrieves a typed value from JSON at the specified path

func GetTypedWithDefault ΒΆ

func GetTypedWithDefault[T any](jsonStr, path string, defaultValue T, opts ...*ProcessorOptions) T

GetTypedWithDefault retrieves a typed value from JSON at the specified path with a default fallback Returns the default value only when an error occurs (e.g., path not found) Valid zero values (0, false, "") are returned as-is

func GetTypedWithProcessor ΒΆ

func GetTypedWithProcessor[T any](processor *Processor, jsonStr, path string, opts ...*ProcessorOptions) (T, error)

GetTypedWithProcessor retrieves a typed value from JSON using a specific processor

func GetWithDefault ΒΆ

func GetWithDefault(jsonStr, path string, defaultValue any, opts ...*ProcessorOptions) any

GetWithDefault retrieves a value from JSON at the specified path with a default fallback

func HTMLEscape ΒΆ

func HTMLEscape(dst *bytes.Buffer, src []byte)

HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028, and U+2029 characters escaped. This function is 100% compatible with encoding/json.HTMLEscape.

func HTMLEscapeBuffer ΒΆ added in v1.1.0

func HTMLEscapeBuffer(dst *bytes.Buffer, src []byte, opts ...*ProcessorOptions)

HTMLEscapeBuffer is an alias for HTMLEscape for buffer operations

func Indent ΒΆ

func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error

Indent appends to dst an indented form of the JSON-encoded src. This function is 100% compatible with encoding/json.Indent.

func IndentBuffer ΒΆ added in v1.1.0

func IndentBuffer(dst *bytes.Buffer, src []byte, prefix, indent string, opts ...*ProcessorOptions) error

IndentBuffer is an alias for Indent for buffer operations

func InternKey ΒΆ added in v1.2.0

func InternKey(key string) string

InternKey returns an interned copy of the key string If the key has been seen before, returns the existing copy Otherwise, stores and returns a copy of the key

func InternMapKeys ΒΆ added in v1.2.0

func InternMapKeys(m map[string]any)

InternMapKeys interns all keys in a map PERFORMANCE: Reduces memory usage when the same keys appear in multiple maps

func IsContainer ΒΆ

func IsContainer(data any) bool

IsContainer checks if the data is a container type (map or slice)

func IsInteger ΒΆ

func IsInteger(s string) bool

IsInteger checks if a string represents an integer value

func IsLargeNumber ΒΆ

func IsLargeNumber(numStr string) bool

IsLargeNumber checks if a string represents a number that's too large for standard numeric types

func IsNumeric ΒΆ

func IsNumeric(s string) bool

IsNumeric checks if a string represents a numeric value

func IsRetryable ΒΆ added in v1.0.10

func IsRetryable(err error) bool

IsRetryable determines if an error is retryable

func IsScientificNotation ΒΆ

func IsScientificNotation(s string) bool

IsScientificNotation checks if a string represents a number in scientific notation

func IsSecurityRelated ΒΆ added in v1.0.10

func IsSecurityRelated(err error) bool

IsSecurityRelated determines if an error is security-related

func IsUserError ΒΆ added in v1.0.10

func IsUserError(err error) bool

IsUserError determines if an error is caused by user input

func IsValidJSON ΒΆ added in v1.0.10

func IsValidJSON(jsonStr string) bool

IsValidJSON quickly checks if a string is valid JSON

func IsValidPath ΒΆ

func IsValidPath(path string) bool

IsValidPath checks if a path expression is valid

func KeyInternCacheSize ΒΆ added in v1.2.0

func KeyInternCacheSize() int

KeyInternCacheSize returns the number of interned keys

func LoadFromFile ΒΆ

func LoadFromFile(filePath string, opts ...*ProcessorOptions) (string, error)

LoadFromFile loads JSON data from a file with optional processor configuration Uses the default processor with support for ProcessorOptions such as security validation

func Marshal ΒΆ

func Marshal(v any) ([]byte, error)

Marshal returns the JSON encoding of v. This function is 100% compatible with encoding/json.Marshal.

func MarshalIndent ΒΆ

func MarshalIndent(v any, prefix, indent string) ([]byte, error)

MarshalIndent is like Marshal but applies indentation to format the output. This function is 100% compatible with encoding/json.MarshalIndent.

func MarshalToFile ΒΆ added in v1.0.6

func MarshalToFile(path string, data any, pretty ...bool) error

MarshalToFile converts data to JSON and saves it to the specified file. This is a convenience function that combines Marshal and file writing operations. Uses the default processor for security validation and encoding.

Parameters:

  • path: file path where JSON will be saved (directories are created automatically)
  • data: any Go value to be marshaled to JSON
  • pretty: optional parameter - true for formatted JSON, false for compact (default: false)

Returns error if marshaling fails or file cannot be written.

Special behavior for string and []byte inputs:

  • If data is a JSON string, it will be parsed first to prevent double-encoding.
  • If data is []byte containing JSON, it will be parsed first.

func MergeJson ΒΆ

func MergeJson(json1, json2 string) (string, error)

MergeJson merges two JSON objects using deep merge strategy For nested objects, it recursively merges keys (union merge) For primitive values and arrays, the value from json2 takes precedence

func NewMapWithEstimatedSize ΒΆ added in v1.2.0

func NewMapWithEstimatedSize(jsonBytes []byte) map[string]any

NewMapWithEstimatedSize creates a new map with capacity estimated from JSON bytes

func NewProcessorUtils ΒΆ

func NewProcessorUtils() *processorUtils

NewProcessorUtils creates a new processor utils instance

func NewSliceWithEstimatedSize ΒΆ added in v1.2.0

func NewSliceWithEstimatedSize(jsonBytes []byte) []any

NewSliceWithEstimatedSize creates a new slice with capacity estimated from JSON bytes

func ParseArrayIndexGlobal deprecated added in v1.0.7

func ParseArrayIndexGlobal(indexStr string) int

ParseArrayIndexGlobal is a package-level function for backward compatibility.

Deprecated: Use ArrayHelper.ParseArrayIndex method instead for better testability. This function will be removed in a future major version (v2.0.0).

func ParseBool ΒΆ

func ParseBool(s string) (bool, error)

ParseBool parses a string to boolean with error handling

func ParseFloat ΒΆ

func ParseFloat(s string) (float64, error)

ParseFloat parses a string to float64 with error handling

func ParseInt ΒΆ

func ParseInt(s string) (int, error)

ParseInt parses a string to integer with error handling

func ParseJSONL ΒΆ added in v1.2.0

func ParseJSONL(data []byte) ([]any, error)

ParseJSONL parses JSONL data from a byte slice

func ParseJSONLInto ΒΆ added in v1.2.0

func ParseJSONLInto[T any](data []byte) ([]T, error)

ParseJSONLInto parses JSONL data into typed values

func PreservingUnmarshal ΒΆ

func PreservingUnmarshal(data []byte, v any, preserveNumbers bool) error

PreservingUnmarshal unmarshals JSON with number preservation

func Print ΒΆ added in v1.1.0

func Print(data any)

Print prints any Go value as JSON to stdout in compact format. Note: Writes errors to stderr. Use PrintE for error handling.

func PrintE ΒΆ added in v1.2.0

func PrintE(data any) error

PrintE prints any Go value as JSON to stdout in compact format. Returns an error instead of writing to stderr, allowing callers to handle errors.

func PrintPretty ΒΆ added in v1.1.0

func PrintPretty(data any)

PrintPretty prints any Go value as formatted JSON to stdout. Note: Writes errors to stderr. Use PrintPrettyE for error handling.

func PrintPrettyE ΒΆ added in v1.2.0

func PrintPrettyE(data any) error

PrintPrettyE prints any Go value as formatted JSON to stdout. Returns an error instead of writing to stderr, allowing callers to handle errors.

func PutEncodeBuffer ΒΆ added in v1.2.0

func PutEncodeBuffer(buf []byte)

PutEncodeBuffer returns a buffer to the pool

func PutEncodeConfig ΒΆ added in v1.2.2

func PutEncodeConfig(cfg *EncodeConfig)

PutEncodeConfig returns an EncodeConfig to the pool PERFORMANCE: Call this after using DefaultEncodeConfig to reduce GC pressure

func PutPooledDecoder ΒΆ added in v1.2.0

func PutPooledDecoder(dec *Decoder)

PutPooledDecoder returns a decoder to the global pool

func PutResultBuffer ΒΆ added in v1.2.0

func PutResultBuffer(buf *[]byte)

PutResultBuffer returns a buffer to the pool

func SafeConvertToInt64 ΒΆ

func SafeConvertToInt64(value any) (int64, error)

SafeConvertToInt64 safely converts any value to int64 with error handling

func SafeConvertToUint64 ΒΆ

func SafeConvertToUint64(value any) (uint64, error)

SafeConvertToUint64 safely converts any value to uint64 with error handling

func SafeTypeAssert ΒΆ

func SafeTypeAssert[T any](value any) (T, bool)

SafeTypeAssert performs a safe type assertion with generics

func SanitizeKey ΒΆ

func SanitizeKey(key string) string

SanitizeKey sanitizes a key for safe use in maps

func SaveToFile ΒΆ

func SaveToFile(filePath string, data any, pretty ...bool) error

SaveToFile saves JSON data to a file with optional formatting This function accepts any Go value and converts it to JSON before saving.

Special behavior for string and []byte inputs:

  • If data is a JSON string, it will be parsed first to prevent double-encoding.
  • If data is []byte containing JSON, it will be parsed first.
  • This ensures that SaveToFile("file.json", `{"a":1}`) writes {"a":1} not "{\"a\":1}"

Uses the default processor for security validation and encoding.

func Set ΒΆ

func Set(jsonStr, path string, value any, opts ...*ProcessorOptions) (string, error)

Set sets a value in JSON at the specified path Returns:

  • On success: modified JSON string and nil error
  • On failure: original unmodified JSON string and error information

func SetGlobalProcessor ΒΆ

func SetGlobalProcessor(processor *Processor)

SetGlobalProcessor sets a custom global processor (thread-safe)

func SetMultiple ΒΆ

func SetMultiple(jsonStr string, updates map[string]any, opts ...*ProcessorOptions) (string, error)

SetMultiple sets multiple values using a map of path-value pairs

func SetMultipleWithAdd ΒΆ

func SetMultipleWithAdd(jsonStr string, updates map[string]any, opts ...*ProcessorOptions) (string, error)

SetMultipleWithAdd sets multiple values with automatic path creation

func SetWithAdd ΒΆ

func SetWithAdd(jsonStr, path string, value any) (string, error)

SetWithAdd sets a value with automatic path creation Returns:

  • On success: modified JSON string and nil error
  • On failure: original unmodified JSON string and error information

func ShutdownGlobalProcessor ΒΆ

func ShutdownGlobalProcessor()

ShutdownGlobalProcessor shuts down the global processor

func SmartNumberConversion ΒΆ

func SmartNumberConversion(value any) any

SmartNumberConversion provides intelligent number type conversion

func StreamArrayCount ΒΆ added in v1.2.0

func StreamArrayCount(reader io.Reader) (int, error)

StreamArrayCount counts elements without storing them Memory-efficient for just getting array length

func StreamArrayFilter ΒΆ added in v1.2.0

func StreamArrayFilter(reader io.Reader, predicate func(any) bool) ([]any, error)

StreamArrayFilter filters array elements during streaming Only elements that pass the predicate are kept

func StreamArrayFirst ΒΆ added in v1.2.0

func StreamArrayFirst(reader io.Reader, predicate func(any) bool) (any, bool, error)

StreamArrayFirst returns the first element that matches a predicate Stops processing as soon as a match is found

func StreamArrayForEach ΒΆ added in v1.2.0

func StreamArrayForEach(reader io.Reader, fn func(int, any) error) error

StreamArrayForEach processes each element without collecting results Useful for side effects like writing to a database or file

func StreamArrayMap ΒΆ added in v1.2.0

func StreamArrayMap(reader io.Reader, transform func(any) any) ([]any, error)

StreamArrayMap transforms array elements during streaming Each element is transformed using the provided function

func StreamArrayReduce ΒΆ added in v1.2.0

func StreamArrayReduce(reader io.Reader, initial any, reducer func(any, any) any) (any, error)

StreamArrayReduce reduces array elements to a single value during streaming The reducer function receives the accumulated value and current element

func StreamArraySkip ΒΆ added in v1.2.0

func StreamArraySkip(reader io.Reader, n int) ([]any, error)

StreamArraySkip skips the first n elements and returns the rest Useful for pagination

func StreamArrayTake ΒΆ added in v1.2.0

func StreamArrayTake(reader io.Reader, n int) ([]any, error)

StreamArrayTake returns the first n elements from a streaming array Useful for pagination or sampling

func StreamLinesInto ΒΆ added in v1.2.0

func StreamLinesInto[T any](reader io.Reader, fn func(lineNum int, data T) error) ([]T, error)

StreamLinesInto processes JSONL data into a slice of typed values Uses generics for type-safe processing

func StreamLinesIntoWithConfig ΒΆ added in v1.2.0

func StreamLinesIntoWithConfig[T any](reader io.Reader, config JSONLConfig, fn func(lineNum int, data T) error) ([]T, error)

StreamLinesIntoWithConfig processes JSONL data into a slice of typed values with config

func TestProcessorResourcePools ΒΆ

func TestProcessorResourcePools(processor *Processor) bool

TestProcessorResourcePools tests processor resource pool functionality

func ToJSONL ΒΆ added in v1.2.0

func ToJSONL(data []any) ([]byte, error)

ToJSONL converts a slice of values to JSONL format

func ToJSONLString ΒΆ added in v1.2.0

func ToJSONLString(data []any) (string, error)

ToJSONLString converts a slice of values to JSONL format string

func TypeSafeConvert ΒΆ

func TypeSafeConvert[T any](value any) (T, error)

TypeSafeConvert attempts to convert a value to the target type safely

func UnescapeJSONPointer ΒΆ

func UnescapeJSONPointer(s string) string

UnescapeJSONPointer unescapes JSON Pointer special characters

func UnifiedTypeConversion ΒΆ added in v1.0.4

func UnifiedTypeConversion[T any](value any) (T, bool)

UnifiedTypeConversion provides optimized type conversion with comprehensive support

func Unmarshal ΒΆ

func Unmarshal(data []byte, v any) error

Unmarshal parses the JSON-encoded data and stores the result in v. This function is 100% compatible with encoding/json.Unmarshal.

func UnmarshalFromFile ΒΆ added in v1.0.6

func UnmarshalFromFile(path string, v any, opts ...*ProcessorOptions) error

UnmarshalFromFile reads JSON from a file and unmarshals it into v. This is a convenience function that combines file reading and unmarshalling. Uses the default processor for security validation and decoding.

Parameters:

  • path: file path to read JSON from
  • v: pointer to the target variable where JSON will be unmarshaled
  • opts: optional ProcessorOptions for security validation and processing

Returns error if file reading fails or JSON cannot be unmarshaled.

func Valid ΒΆ

func Valid(data []byte) bool

Valid reports whether data is valid JSON. This function is 100% compatible with encoding/json.Valid.

func ValidString ΒΆ added in v1.2.2

func ValidString(jsonStr string) bool

ValidString reports whether the JSON string is valid. This is a convenience wrapper for Valid that accepts a string directly.

func ValidWithOptions ΒΆ added in v1.2.2

func ValidWithOptions(jsonStr string, opts ...*ProcessorOptions) (bool, error)

ValidWithOptions reports whether the JSON string is valid with optional processor options. Returns both the validation result and any error that occurred during validation.

func ValidateConfig ΒΆ

func ValidateConfig(config *Config) error

ValidateConfig validates configuration values and applies corrections

func ValidateOptions ΒΆ

func ValidateOptions(options *ProcessorOptions) error

ValidateOptions validates processor options with enhanced checks

func ValidatePath ΒΆ

func ValidatePath(path string) error

ValidatePath validates a path expression and returns detailed error information

func WarmupPathCache ΒΆ added in v1.2.0

func WarmupPathCache(commonPaths []string)

WarmupPathCache pre-populates the path cache with common paths PERFORMANCE: Reduces first-access latency for frequently used paths

func WarmupPathCacheWithProcessor ΒΆ added in v1.2.0

func WarmupPathCacheWithProcessor(processor *Processor, commonPaths []string)

WarmupPathCacheWithProcessor pre-populates the path cache using a specific processor PERFORMANCE: Useful when using custom processor configurations

func WrapError ΒΆ added in v1.0.6

func WrapError(err error, op, message string) error

WrapError wraps an error with additional context

func WrapPathError ΒΆ added in v1.0.6

func WrapPathError(err error, op, path, message string) error

WrapPathError wraps an error with path context

Types ΒΆ

type ArrayExtensionError ΒΆ

type ArrayExtensionError struct {
	CurrentLength  int
	RequiredLength int
	TargetIndex    int
	Value          any
	Message        string
}

ArrayExtensionError signals that array extension is needed

func (*ArrayExtensionError) Error ΒΆ

func (e *ArrayExtensionError) Error() string

type ArrayExtensionNeededError ΒΆ

type ArrayExtensionNeededError struct {
	RequiredLength int
	CurrentLength  int
	Start          int
	End            int
	Step           int
	Value          any
}

ArrayExtensionNeededError signals that array extension is needed

func (*ArrayExtensionNeededError) Error ΒΆ

func (e *ArrayExtensionNeededError) Error() string

type ArrayHelper ΒΆ added in v1.0.7

type ArrayHelper struct{}

ArrayHelper provides centralized array operation utilities

func (*ArrayHelper) ClampIndex ΒΆ added in v1.0.7

func (ah *ArrayHelper) ClampIndex(index, length int) int

ClampIndex clamps an index to valid bounds [0, length]

func (*ArrayHelper) CompactArray ΒΆ added in v1.0.7

func (ah *ArrayHelper) CompactArray(arr []any) []any

CompactArray removes nil values and deletion markers from an array Optimized: first pass counts removable elements, avoiding allocation if none found

func (*ArrayHelper) ExtendArray ΒΆ added in v1.0.7

func (ah *ArrayHelper) ExtendArray(arr []any, targetLength int) []any

ExtendArray extends an array to the specified length, filling with nil values

func (*ArrayHelper) GetElement ΒΆ added in v1.0.7

func (ah *ArrayHelper) GetElement(arr []any, index int) (any, bool)

GetElement safely gets an element from an array with bounds checking Delegates to internal implementation for consistency

func (*ArrayHelper) NormalizeIndex ΒΆ added in v1.0.7

func (ah *ArrayHelper) NormalizeIndex(index, length int) int

NormalizeIndex converts negative indices to positive indices Delegates to internal implementation for consistency

func (*ArrayHelper) ParseArrayIndex ΒΆ added in v1.0.7

func (ah *ArrayHelper) ParseArrayIndex(indexStr string) int

ParseArrayIndex parses an array index from a string Delegates to internal implementation for consistency

func (*ArrayHelper) PerformSlice ΒΆ added in v1.0.7

func (ah *ArrayHelper) PerformSlice(arr []any, start, end, step int) []any

PerformSlice performs array slicing with step support Delegates to internal implementation for consistency

func (*ArrayHelper) SetElement ΒΆ added in v1.0.7

func (ah *ArrayHelper) SetElement(arr []any, index int, value any) bool

SetElement safely sets an element in an array with bounds checking Note: This does NOT support negative indices for bounds checking

func (*ArrayHelper) ValidateBounds ΒΆ added in v1.0.7

func (ah *ArrayHelper) ValidateBounds(index, length int) bool

ValidateBounds checks if an index is within valid bounds [0, length) Note: This does NOT support negative indices (unlike IsValidIndex in internal)

type BatchIterator ΒΆ added in v1.2.0

type BatchIterator struct {
	// contains filtered or unexported fields
}

BatchIterator processes arrays in batches for efficient bulk operations

func NewBatchIterator ΒΆ added in v1.2.0

func NewBatchIterator(data []any, batchSize int) *BatchIterator

NewBatchIterator creates a new batch iterator

func (*BatchIterator) CurrentIndex ΒΆ added in v1.2.0

func (it *BatchIterator) CurrentIndex() int

CurrentIndex returns the current position in the array

func (*BatchIterator) HasNext ΒΆ added in v1.2.0

func (it *BatchIterator) HasNext() bool

HasNext returns true if there are more batches to process

func (*BatchIterator) NextBatch ΒΆ added in v1.2.0

func (it *BatchIterator) NextBatch() []any

NextBatch returns the next batch of elements Returns nil when no more batches are available

func (*BatchIterator) Remaining ΒΆ added in v1.2.0

func (it *BatchIterator) Remaining() int

Remaining returns the number of remaining elements

func (*BatchIterator) Reset ΒΆ added in v1.2.0

func (it *BatchIterator) Reset()

Reset resets the iterator to the beginning

func (*BatchIterator) TotalBatches ΒΆ added in v1.2.0

func (it *BatchIterator) TotalBatches() int

TotalBatches returns the total number of batches

type BatchOperation ΒΆ

type BatchOperation struct {
	Type    string `json:"type"`
	JSONStr string `json:"json_str"`
	Path    string `json:"path"`
	Value   any    `json:"value"`
	ID      string `json:"id"`
}

BatchOperation represents a single operation in a batch

type BatchResult ΒΆ

type BatchResult struct {
	ID     string `json:"id"`
	Result any    `json:"result"`
	Error  error  `json:"error"`
}

BatchResult represents the result of a batch operation

func ProcessBatch ΒΆ added in v1.1.0

func ProcessBatch(operations []BatchOperation, opts ...*ProcessorOptions) ([]BatchResult, error)

ProcessBatch processes multiple JSON operations in a single batch. This is more efficient than processing each operation individually.

type BenchmarkHelper ΒΆ

type BenchmarkHelper struct {
	// contains filtered or unexported fields
}

BenchmarkHelper provides utilities for benchmark tests

func NewBenchmarkHelper ΒΆ

func NewBenchmarkHelper(b *testing.B) *BenchmarkHelper

NewBenchmarkHelper creates a new benchmark helper

func (*BenchmarkHelper) MeasureMemory ΒΆ

func (bh *BenchmarkHelper) MeasureMemory(fn func())

MeasureMemory measures memory allocations during benchmark

type BulkProcessor ΒΆ added in v1.2.0

type BulkProcessor struct {
	// contains filtered or unexported fields
}

BulkProcessor handles multiple operations efficiently

func NewBulkProcessor ΒΆ added in v1.2.0

func NewBulkProcessor(processor *Processor, batchSize int) *BulkProcessor

NewBulkProcessor creates a bulk processor

func (*BulkProcessor) BulkGet ΒΆ added in v1.2.0

func (bp *BulkProcessor) BulkGet(jsonStr string, paths []string) (map[string]any, error)

BulkGet performs multiple Get operations efficiently

type CacheKey ΒΆ

type CacheKey struct {
	Operation string
	JSONStr   string
	Path      string
	Options   string
}

CacheKey represents a cache key for operations

type CacheStats ΒΆ

type CacheStats struct {
	HitCount         int64        `json:"hit_count"`
	MissCount        int64        `json:"miss_count"`
	TotalMemory      int64        `json:"total_memory"`
	HitRatio         float64      `json:"hit_ratio"`
	MemoryEfficiency float64      `json:"memory_efficiency"`
	Evictions        int64        `json:"evictions"`
	ShardCount       int          `json:"shard_count"`
	ShardStats       []ShardStats `json:"shard_stats"`
}

CacheStats provides comprehensive cache statistics

type CheckResult ΒΆ

type CheckResult struct {
	Healthy bool   `json:"healthy"`
	Message string `json:"message"`
}

CheckResult represents the result of a single health check

type ChunkedReader ΒΆ added in v1.2.0

type ChunkedReader struct {
	// contains filtered or unexported fields
}

ChunkedReader reads JSON in chunks for memory efficiency

func NewChunkedReader ΒΆ added in v1.2.0

func NewChunkedReader(reader io.Reader, chunkSize int) *ChunkedReader

NewChunkedReader creates a new chunked reader

func (*ChunkedReader) ReadArray ΒΆ added in v1.2.0

func (cr *ChunkedReader) ReadArray(fn func(item any) bool) error

ReadArray reads array elements one at a time

func (*ChunkedReader) ReadObject ΒΆ added in v1.2.0

func (cr *ChunkedReader) ReadObject(fn func(key string, value any) bool) error

ReadObject reads object key-value pairs one at a time

type ChunkedWriter ΒΆ added in v1.2.0

type ChunkedWriter struct {
	// contains filtered or unexported fields
}

ChunkedWriter writes JSON in chunks for memory efficiency

func NewChunkedWriter ΒΆ added in v1.2.0

func NewChunkedWriter(writer io.Writer, chunkSize int, isArray bool) *ChunkedWriter

NewChunkedWriter creates a new chunked writer

func (*ChunkedWriter) Count ΒΆ added in v1.2.0

func (cw *ChunkedWriter) Count() int

Count returns the number of items written

func (*ChunkedWriter) Flush ΒΆ added in v1.2.0

func (cw *ChunkedWriter) Flush(final bool) error

Flush writes the buffer to the underlying writer

func (*ChunkedWriter) WriteItem ΒΆ added in v1.2.0

func (cw *ChunkedWriter) WriteItem(item any) error

WriteItem writes a single item to the chunk

func (*ChunkedWriter) WriteKeyValue ΒΆ added in v1.2.0

func (cw *ChunkedWriter) WriteKeyValue(key string, value any) error

WriteKeyValue writes a key-value pair to the chunk

type ConcurrencyTester ΒΆ

type ConcurrencyTester struct {
	// contains filtered or unexported fields
}

ConcurrencyTester helps test concurrent operations

func NewConcurrencyTester ΒΆ

func NewConcurrencyTester(t *testing.T, concurrency, iterations int) *ConcurrencyTester

NewConcurrencyTester creates a new concurrency tester

func (*ConcurrencyTester) Run ΒΆ

func (ct *ConcurrencyTester) Run(operation func(workerID, iteration int) error)

Run runs concurrent test operations

type Config ΒΆ

type Config struct {
	// Cache settings
	MaxCacheSize int           `json:"max_cache_size"`
	CacheTTL     time.Duration `json:"cache_ttl"`
	EnableCache  bool          `json:"enable_cache"`

	// Size limits
	MaxJSONSize  int64 `json:"max_json_size"`
	MaxPathDepth int   `json:"max_path_depth"`
	MaxBatchSize int   `json:"max_batch_size"`

	// Security limits
	MaxNestingDepthSecurity   int   `json:"max_nesting_depth"`
	MaxSecurityValidationSize int64 `json:"max_security_validation_size"`
	MaxObjectKeys             int   `json:"max_object_keys"`
	MaxArrayElements          int   `json:"max_array_elements"`

	// Concurrency
	MaxConcurrency    int `json:"max_concurrency"`
	ParallelThreshold int `json:"parallel_threshold"`

	// Processing
	EnableValidation bool `json:"enable_validation"`
	StrictMode       bool `json:"strict_mode"`
	CreatePaths      bool `json:"create_paths"`
	CleanupNulls     bool `json:"cleanup_nulls"`
	CompactArrays    bool `json:"compact_arrays"`

	// Additional options
	EnableMetrics     bool `json:"enable_metrics"`
	EnableHealthCheck bool `json:"enable_health_check"`
	AllowComments     bool `json:"allow_comments"`
	PreserveNumbers   bool `json:"preserve_numbers"`
	ValidateInput     bool `json:"validate_input"`
	ValidateFilePath  bool `json:"validate_file_path"`
	// FullSecurityScan enables full (non-sampling) security validation for all JSON input.
	//
	// When false (default): Large JSON (>4KB) uses optimized sampling with:
	//   - 16KB beginning section scan
	//   - 8KB end section scan
	//   - 15-30 distributed middle samples with 512-byte overlap
	//   - Critical patterns (__proto__, constructor, prototype) always fully scanned
	//   - Suspicious character density triggers automatic full scan
	//
	// When true: All JSON is fully scanned regardless of size.
	//
	// SECURITY RECOMMENDATION: Enable FullSecurityScan when:
	//   - Processing untrusted input from external sources
	//   - Handling sensitive data (authentication, financial, personal)
	//   - Building public-facing APIs or web services
	//   - Compliance requirements mandate full content inspection
	//
	// PERFORMANCE NOTE: Full scanning adds ~10-30% overhead for JSON >100KB.
	// For trusted internal services with large JSON payloads, sampling mode is acceptable.
	FullSecurityScan bool `json:"full_security_scan"`
}

Config holds configuration for the JSON processor

func DefaultConfig ΒΆ

func DefaultConfig() *Config

DefaultConfig returns the default configuration. Creates a new instance each time to allow modifications without affecting other callers. PERFORMANCE NOTE: For read-only access in hot paths, cache the result.

func FastConfig ΒΆ added in v1.2.2

func FastConfig() *Config

FastConfig returns a configuration optimized for trusted internal services. This configuration maximizes performance by reducing security overhead and should ONLY be used when you trust the source of JSON data.

Key characteristics:

  • Sampling-based security validation (faster but less thorough)
  • Larger limits for trusted internal data
  • Caching enabled with larger cache
  • Non-strict mode for flexible parsing

SECURITY WARNING: Do NOT use this configuration for:

  • Public APIs
  • User-submitted data
  • External webhooks
  • Any untrusted input

Use this for: Internal microservices, config files, trusted data pipelines.

func HighSecurityConfig ΒΆ

func HighSecurityConfig() *Config

HighSecurityConfig returns a configuration with enhanced security settings for processing untrusted input from external sources.

SECURITY: This configuration enables FullSecurityScan by default, which disables sampling-based validation and performs complete security scanning on all JSON input. Use this for public APIs, authentication endpoints, financial data processing, or any scenario with untrusted input.

func LargeDataConfig ΒΆ

func LargeDataConfig() *Config

LargeDataConfig returns a configuration optimized for large JSON datasets

func MinimalConfig ΒΆ added in v1.2.2

func MinimalConfig() *Config

MinimalConfig returns a configuration with minimal overhead for maximum performance. This configuration disables most safety features and should only be used in controlled environments where you have complete control over the JSON data.

Key characteristics:

  • Security validation disabled
  • Caching disabled
  • Maximum limits
  • No strict mode

SECURITY WARNING: This configuration provides NO protection against:

  • Malformed JSON attacks
  • Deeply nested payload attacks
  • Memory exhaustion attacks
  • Prototype pollution attempts

Use this for: Benchmarking, testing, trusted in-memory processing.

func WebAPIConfig ΒΆ added in v1.2.2

func WebAPIConfig() *Config

WebAPIConfig returns a configuration optimized for web API handlers. This configuration provides a balance between security and performance for public-facing APIs that receive JSON input from external clients.

Key characteristics:

  • Full security scan enabled for all input
  • Moderate limits suitable for typical API payloads
  • Strict mode enabled for predictable parsing
  • Caching enabled for repeated operations

Use this for: REST APIs, GraphQL endpoints, webhooks, public APIs.

func (*Config) Clone ΒΆ added in v1.0.6

func (c *Config) Clone() *Config

Clone creates a copy of the configuration. Note: Config currently contains only value types (int, bool, time.Duration), so a shallow copy is sufficient. If reference types (slices, maps, pointers) are added in the future, this method must be updated to perform deep copying.

func (*Config) GetCacheTTL ΒΆ

func (c *Config) GetCacheTTL() time.Duration

func (*Config) GetMaxCacheSize ΒΆ

func (c *Config) GetMaxCacheSize() int

func (*Config) GetMaxConcurrency ΒΆ

func (c *Config) GetMaxConcurrency() int

func (*Config) GetMaxJSONSize ΒΆ

func (c *Config) GetMaxJSONSize() int64

func (*Config) GetMaxNestingDepth ΒΆ

func (c *Config) GetMaxNestingDepth() int

func (*Config) GetMaxPathDepth ΒΆ

func (c *Config) GetMaxPathDepth() int

func (*Config) GetSecurityLimits ΒΆ

func (c *Config) GetSecurityLimits() map[string]any

GetSecurityLimits returns a summary of current security limits

func (*Config) IsCacheEnabled ΒΆ

func (c *Config) IsCacheEnabled() bool

ConfigInterface implementation methods

func (*Config) IsCommentsAllowed ΒΆ added in v1.0.10

func (c *Config) IsCommentsAllowed() bool

func (*Config) IsHealthCheckEnabled ΒΆ

func (c *Config) IsHealthCheckEnabled() bool

func (*Config) IsMetricsEnabled ΒΆ

func (c *Config) IsMetricsEnabled() bool

func (*Config) IsStrictMode ΒΆ

func (c *Config) IsStrictMode() bool

func (*Config) ShouldCleanupNulls ΒΆ

func (c *Config) ShouldCleanupNulls() bool

func (*Config) ShouldCompactArrays ΒΆ

func (c *Config) ShouldCompactArrays() bool

func (*Config) ShouldCreatePaths ΒΆ

func (c *Config) ShouldCreatePaths() bool

func (*Config) ShouldPreserveNumbers ΒΆ added in v1.0.10

func (c *Config) ShouldPreserveNumbers() bool

func (*Config) ShouldValidateFilePath ΒΆ

func (c *Config) ShouldValidateFilePath() bool

func (*Config) ShouldValidateInput ΒΆ

func (c *Config) ShouldValidateInput() bool

func (*Config) Validate ΒΆ added in v1.0.6

func (c *Config) Validate() error

Validate validates the configuration and applies corrections

type ConfigInterface ΒΆ added in v1.0.7

type ConfigInterface interface {
	IsCacheEnabled() bool
	GetMaxCacheSize() int
	GetCacheTTL() time.Duration
	GetMaxJSONSize() int64
	GetMaxPathDepth() int
	GetMaxConcurrency() int
	IsMetricsEnabled() bool
	IsStrictMode() bool
	IsCommentsAllowed() bool
	ShouldPreserveNumbers() bool
	ShouldCreatePaths() bool
	ShouldCleanupNulls() bool
	ShouldCompactArrays() bool
	ShouldValidateInput() bool
	GetMaxNestingDepth() int
}

ConfigInterface defines the interface for configuration objects

type CustomEncoder ΒΆ

type CustomEncoder struct {
	// contains filtered or unexported fields
}

CustomEncoder provides advanced JSON encoding with configurable options

func NewCustomEncoder ΒΆ

func NewCustomEncoder(config *EncodeConfig) *CustomEncoder

NewCustomEncoder creates a new custom encoder with the given configuration

func (*CustomEncoder) Close ΒΆ

func (e *CustomEncoder) Close()

Close releases the encoder's buffers back to the pool

func (*CustomEncoder) Encode ΒΆ

func (e *CustomEncoder) Encode(value any) (string, error)

Encode encodes the given value to JSON string using custom options

type Decoder ΒΆ

type Decoder struct {
	// contains filtered or unexported fields
}

Decoder reads and decodes JSON values from an input stream. This type is fully compatible with encoding/json.Decoder.

func GetPooledDecoder ΒΆ added in v1.2.0

func GetPooledDecoder(r io.Reader) *Decoder

GetPooledDecoder gets a decoder from the global pool PERFORMANCE: Use this for streaming scenarios to reduce allocations

func NewDecoder ΒΆ

func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a new decoder that reads from r. This function is fully compatible with encoding/json.NewDecoder.

func (*Decoder) Buffered ΒΆ

func (dec *Decoder) Buffered() io.Reader

func (*Decoder) Decode ΒΆ

func (dec *Decoder) Decode(v any) error

Decode reads the next JSON-encoded value from its input and stores it in v.

func (*Decoder) DisallowUnknownFields ΒΆ

func (dec *Decoder) DisallowUnknownFields()

func (*Decoder) InputOffset ΒΆ

func (dec *Decoder) InputOffset() int64

func (*Decoder) More ΒΆ

func (dec *Decoder) More() bool

func (*Decoder) Token ΒΆ

func (dec *Decoder) Token() (Token, error)

Token returns the next JSON token in the input stream. At the end of the input stream, Token returns nil, io.EOF.

func (*Decoder) UseNumber ΒΆ

func (dec *Decoder) UseNumber()

type Delim ΒΆ

type Delim rune

Delim is a JSON delimiter.

func (Delim) String ΒΆ

func (d Delim) String() string

type DetailedStats ΒΆ

type DetailedStats struct {
	Stats Stats `json:"stats"`
	// contains filtered or unexported fields
}

DetailedStats provides comprehensive processor statistics (internal debugging)

type EncodeConfig ΒΆ

type EncodeConfig struct {
	Pretty          bool   `json:"pretty"`
	Indent          string `json:"indent"`
	Prefix          string `json:"prefix"`
	EscapeHTML      bool   `json:"escape_html"`
	SortKeys        bool   `json:"sort_keys"`
	ValidateUTF8    bool   `json:"validate_utf8"`
	MaxDepth        int    `json:"max_depth"`
	DisallowUnknown bool   `json:"disallow_unknown"`

	// Number formatting
	PreserveNumbers bool `json:"preserve_numbers"`
	FloatPrecision  int  `json:"float_precision"`
	FloatTruncate   bool `json:"float_truncate"` // Truncate instead of round when FloatPrecision >= 0

	// Character escaping
	DisableEscaping bool `json:"disable_escaping"`
	EscapeUnicode   bool `json:"escape_unicode"`
	EscapeSlash     bool `json:"escape_slash"`
	EscapeNewlines  bool `json:"escape_newlines"`
	EscapeTabs      bool `json:"escape_tabs"`

	// Null handling
	IncludeNulls  bool            `json:"include_nulls"`
	CustomEscapes map[rune]string `json:"custom_escapes,omitempty"`
}

EncodeConfig provides advanced encoding configuration (for complex use cases)

func DefaultEncodeConfig ΒΆ

func DefaultEncodeConfig() *EncodeConfig

DefaultEncodeConfig returns default encoding configuration PERFORMANCE: Uses sync.Pool to reduce allocations in hot paths

func NewCleanConfig ΒΆ

func NewCleanConfig() *EncodeConfig

NewCleanConfig creates a configuration that omits null and empty values

func NewPrettyConfig ΒΆ

func NewPrettyConfig() *EncodeConfig

NewPrettyConfig returns configuration for pretty-printed JSON

func NewReadableConfig ΒΆ

func NewReadableConfig() *EncodeConfig

NewReadableConfig creates a configuration for human-readable JSON with minimal escaping

func NewWebSafeConfig ΒΆ

func NewWebSafeConfig() *EncodeConfig

NewWebSafeConfig creates a configuration for web-safe JSON

func (*EncodeConfig) Clone ΒΆ

func (c *EncodeConfig) Clone() *EncodeConfig

Clone creates a deep copy of the EncodeConfig

type Encoder ΒΆ

type Encoder struct {
	// contains filtered or unexported fields
}

Encoder writes JSON values to an output stream. This type is fully compatible with encoding/json.Encoder.

func NewEncoder ΒΆ

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new encoder that writes to w. This function is fully compatible with encoding/json.NewEncoder.

func (*Encoder) Encode ΒΆ

func (enc *Encoder) Encode(v any) error

Encode writes the JSON encoding of v to the stream, followed by a newline character.

See the documentation for Marshal for details about the conversion of Go values to JSON.

func (*Encoder) SetEscapeHTML ΒΆ

func (enc *Encoder) SetEscapeHTML(on bool)

SetEscapeHTML specifies whether problematic HTML characters should be escaped inside JSON quoted strings. The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e to avoid certain safety problems that can arise when embedding JSON in HTML.

In non-HTML settings where the escaping interferes with the readability of the output, SetEscapeHTML(false) disables this behavior.

func (*Encoder) SetIndent ΒΆ

func (enc *Encoder) SetIndent(prefix, indent string)

SetIndent instructs the encoder to format each subsequent encoded value as if indented by the package-level function Indent(dst, src, prefix, indent). Calling SetIndent("", "") disables indentation.

type ExtractionContext ΒΆ

type ExtractionContext struct {
	OriginalContainers []any  // Original containers that hold the target arrays
	ArrayFieldName     string // Name of the array field being operated on
	TargetIndices      []int  // Target indices for each container
	OperationType      string // Type of operation: "get", "set", "delete"
}

ExtractionContext represents the context for extraction operations

type ExtractionGroup ΒΆ added in v1.0.8

type ExtractionGroup = internal.ExtractionGroup

ExtractionGroup represents a group of consecutive extraction segments

type HealthStatus ΒΆ

type HealthStatus struct {
	Timestamp time.Time              `json:"timestamp"`
	Healthy   bool                   `json:"healthy"`
	Checks    map[string]CheckResult `json:"checks"`
}

HealthStatus represents the health status of the processor

func GetHealthStatus ΒΆ added in v1.1.0

func GetHealthStatus() HealthStatus

GetHealthStatus returns the health status of the default processor.

type InvalidUnmarshalError ΒΆ

type InvalidUnmarshalError struct {
	Type reflect.Type
}

InvalidUnmarshalError describes an invalid argument passed to Unmarshal. (The argument to Unmarshal must be a non-nil pointer.)

func (*InvalidUnmarshalError) Error ΒΆ

func (e *InvalidUnmarshalError) Error() string

type IterableValue ΒΆ

type IterableValue struct {
	// contains filtered or unexported fields
}

IterableValue wraps a value to provide convenient access methods Note: Simplified to avoid resource leaks from holding processor/iterator references

func NewIterableValue ΒΆ

func NewIterableValue(data any) *IterableValue

NewIterableValue creates an IterableValue from data

func NewPooledIterableValue ΒΆ added in v1.2.0

func NewPooledIterableValue(data any) *IterableValue

NewPooledIterableValue creates an IterableValue from the pool

func (*IterableValue) Exists ΒΆ

func (iv *IterableValue) Exists(key string) bool

Exists checks if a key or path exists in the object Supports path navigation with dot notation and array indices

func (*IterableValue) ForeachNested ΒΆ

func (iv *IterableValue) ForeachNested(path string, fn func(key any, item *IterableValue))

ForeachNested iterates over nested JSON structures with a path

func (*IterableValue) Get ΒΆ

func (iv *IterableValue) Get(path string) any

Get returns a value by path (supports dot notation and array indices)

func (*IterableValue) GetArray ΒΆ

func (iv *IterableValue) GetArray(key string) []any

GetArray returns an array value by key or path Supports path navigation with dot notation and array indices

func (*IterableValue) GetBool ΒΆ

func (iv *IterableValue) GetBool(key string) bool

GetBool returns a bool value by key or path Supports path navigation with dot notation and array indices

func (*IterableValue) GetBoolWithDefault ΒΆ

func (iv *IterableValue) GetBoolWithDefault(key string, defaultValue bool) bool

GetBoolWithDefault returns a bool value by key or path with a default fallback Supports path navigation with dot notation and array indices

func (*IterableValue) GetData ΒΆ added in v1.2.0

func (iv *IterableValue) GetData() any

GetData returns the underlying data

func (*IterableValue) GetFloat64 ΒΆ

func (iv *IterableValue) GetFloat64(key string) float64

GetFloat64 returns a float64 value by key or path Supports path navigation with dot notation and array indices

func (*IterableValue) GetFloat64WithDefault ΒΆ

func (iv *IterableValue) GetFloat64WithDefault(key string, defaultValue float64) float64

GetFloat64WithDefault returns a float64 value by key or path with a default fallback Supports path navigation with dot notation and array indices

func (*IterableValue) GetInt ΒΆ

func (iv *IterableValue) GetInt(key string) int

GetInt returns an int value by key or path Supports path navigation with dot notation and array indices (e.g., "user.age" or "users[0].id")

func (*IterableValue) GetIntWithDefault ΒΆ

func (iv *IterableValue) GetIntWithDefault(key string, defaultValue int) int

GetIntWithDefault returns an int value by key or path with a default fallback Supports path navigation with dot notation and array indices

func (*IterableValue) GetObject ΒΆ

func (iv *IterableValue) GetObject(key string) map[string]any

GetObject returns an object value by key or path Supports path navigation with dot notation and array indices

func (*IterableValue) GetString ΒΆ

func (iv *IterableValue) GetString(key string) string

GetString returns a string value by key or path Supports path navigation with dot notation and array indices (e.g., "user.address.city" or "users[0].name")

func (*IterableValue) GetStringWithDefault ΒΆ

func (iv *IterableValue) GetStringWithDefault(key string, defaultValue string) string

GetStringWithDefault returns a string value by key or path with a default fallback Supports path navigation with dot notation and array indices

func (*IterableValue) GetWithDefault ΒΆ

func (iv *IterableValue) GetWithDefault(key string, defaultValue any) any

GetWithDefault returns a value by key or path with a default fallback Supports path navigation with dot notation and array indices

func (*IterableValue) IsEmpty ΒΆ

func (iv *IterableValue) IsEmpty(key string) bool

IsEmpty checks if a specific key's or path's value is empty Supports path navigation with dot notation and array indices

func (*IterableValue) IsEmptyData ΒΆ added in v1.0.8

func (iv *IterableValue) IsEmptyData() bool

IsEmptyData checks if the whole value is empty (for backward compatibility)

func (*IterableValue) IsNull ΒΆ

func (iv *IterableValue) IsNull(key string) bool

IsNull checks if a specific key's or path's value is null Supports path navigation with dot notation and array indices

func (*IterableValue) IsNullData ΒΆ added in v1.0.8

func (iv *IterableValue) IsNullData() bool

IsNullData checks if the whole value is null (for backward compatibility)

func (*IterableValue) Release ΒΆ added in v1.2.0

func (iv *IterableValue) Release()

Release returns the IterableValue to the pool

type Iterator ΒΆ

type Iterator struct {
	// contains filtered or unexported fields
}

Iterator represents an iterator over JSON data

func NewIterator ΒΆ

func NewIterator(processor *Processor, data any, opts *ProcessorOptions) *Iterator

NewIterator creates a new Iterator

func (*Iterator) HasNext ΒΆ added in v1.0.8

func (it *Iterator) HasNext() bool

HasNext checks if there are more elements

func (*Iterator) Next ΒΆ added in v1.0.8

func (it *Iterator) Next() (any, bool)

Next returns the next element

type IteratorControl ΒΆ

type IteratorControl int

IteratorControl represents control flags for iteration

const (
	IteratorNormal IteratorControl = iota
	IteratorContinue
	IteratorBreak
)

type JSONLConfig ΒΆ added in v1.2.0

type JSONLConfig struct {
	BufferSize    int  // Buffer size for reading (default: 64KB)
	MaxLineSize   int  // Maximum line size (default: 1MB)
	SkipEmpty     bool // Skip empty lines (default: true)
	SkipComments  bool // Skip lines starting with # or // (default: false)
	ContinueOnErr bool // Continue processing on parse errors (default: false)
}

JSONLConfig holds configuration for JSONL processing

func DefaultJSONLConfig ΒΆ added in v1.2.0

func DefaultJSONLConfig() JSONLConfig

DefaultJSONLConfig returns the default JSONL configuration

type JSONLProcessor ΒΆ added in v1.2.0

type JSONLProcessor struct {
	// contains filtered or unexported fields
}

JSONLProcessor processes JSON Lines format data PERFORMANCE: Uses buffered reading and object pooling for efficiency

func NewJSONLProcessor ΒΆ added in v1.2.0

func NewJSONLProcessor(reader io.Reader) *JSONLProcessor

NewJSONLProcessor creates a new JSONL processor with default configuration

func NewJSONLProcessorWithConfig ΒΆ added in v1.2.0

func NewJSONLProcessorWithConfig(reader io.Reader, config JSONLConfig) *JSONLProcessor

NewJSONLProcessorWithConfig creates a new JSONL processor with custom configuration

func (*JSONLProcessor) Err ΒΆ added in v1.2.0

func (j *JSONLProcessor) Err() error

Err returns any error encountered during processing

func (*JSONLProcessor) GetStats ΒΆ added in v1.2.0

func (j *JSONLProcessor) GetStats() JSONLStats

GetStats returns current processing statistics

func (*JSONLProcessor) Release ΒΆ added in v1.2.0

func (j *JSONLProcessor) Release()

Release returns the processor to the pool

func (*JSONLProcessor) Stop ΒΆ added in v1.2.0

func (j *JSONLProcessor) Stop()

Stop stops the JSONL processor

func (*JSONLProcessor) StreamLines ΒΆ added in v1.2.0

func (j *JSONLProcessor) StreamLines(fn func(lineNum int, data any) bool) error

StreamLines processes JSONL data line by line The callback function receives the line number and parsed data Return false from the callback to stop iteration

func (*JSONLProcessor) StreamLinesParallel ΒΆ added in v1.2.0

func (j *JSONLProcessor) StreamLinesParallel(fn func(lineNum int, data any) error, workers int) error

StreamLinesParallel processes JSONL data in parallel using worker pool PERFORMANCE: Parallel processing for CPU-bound operations on JSONL data

type JSONLStats ΒΆ added in v1.2.0

type JSONLStats struct {
	LinesProcessed int64
	BytesRead      int64
	CurrentLine    int
}

Stats returns processing statistics

type JSONLWriter ΒΆ added in v1.2.0

type JSONLWriter struct {
	// contains filtered or unexported fields
}

JSONLWriter writes JSON Lines format to an io.Writer

func NewJSONLWriter ΒΆ added in v1.2.0

func NewJSONLWriter(writer io.Writer) *JSONLWriter

NewJSONLWriter creates a new JSONL writer

func (*JSONLWriter) Err ΒΆ added in v1.2.0

func (w *JSONLWriter) Err() error

Err returns any error encountered during writing

func (*JSONLWriter) Stats ΒΆ added in v1.2.0

func (w *JSONLWriter) Stats() JSONLStats

Stats returns writing statistics

func (*JSONLWriter) Write ΒΆ added in v1.2.0

func (w *JSONLWriter) Write(data any) error

Write writes a single JSON value as a line

func (*JSONLWriter) WriteAll ΒΆ added in v1.2.0

func (w *JSONLWriter) WriteAll(data []any) error

WriteAll writes multiple JSON values as lines

func (*JSONLWriter) WriteRaw ΒΆ added in v1.2.0

func (w *JSONLWriter) WriteRaw(line []byte) error

WriteRaw writes a raw JSON line (already encoded)

type JsonsError ΒΆ

type JsonsError struct {
	Op      string `json:"op"`      // Operation that failed
	Path    string `json:"path"`    // JSON path where error occurred
	Message string `json:"message"` // Human-readable error message
	Err     error  `json:"err"`     // Underlying error
}

JsonsError represents a JSON processing error with essential context

func (*JsonsError) Error ΒΆ

func (e *JsonsError) Error() string

func (*JsonsError) Is ΒΆ

func (e *JsonsError) Is(target error) bool

Is implements error matching for Go 1.13+ error handling

func (*JsonsError) Unwrap ΒΆ

func (e *JsonsError) Unwrap() error

Unwrap returns the underlying error for error chain support

type LargeFileConfig ΒΆ added in v1.2.0

type LargeFileConfig struct {
	ChunkSize       int64 // Size of each chunk in bytes
	MaxMemory       int64 // Maximum memory to use
	BufferSize      int   // Buffer size for reading
	SamplingEnabled bool  // Enable sampling for very large files
	SampleSize      int   // Number of samples to take
}

LargeFileConfig holds configuration for large file processing

func DefaultLargeFileConfig ΒΆ added in v1.2.0

func DefaultLargeFileConfig() LargeFileConfig

DefaultLargeFileConfig returns the default configuration

type LargeFileProcessor ΒΆ added in v1.2.0

type LargeFileProcessor struct {
	// contains filtered or unexported fields
}

LargeFileProcessor handles processing of large JSON files

func NewLargeFileProcessor ΒΆ added in v1.2.0

func NewLargeFileProcessor(config LargeFileConfig) *LargeFileProcessor

NewLargeFileProcessor creates a new large file processor

func (*LargeFileProcessor) ProcessFile ΒΆ added in v1.2.0

func (lfp *LargeFileProcessor) ProcessFile(filename string, fn func(item any) error) error

ProcessFile processes a large JSON file efficiently

func (*LargeFileProcessor) ProcessFileChunked ΒΆ added in v1.2.0

func (lfp *LargeFileProcessor) ProcessFileChunked(filename string, chunkSize int, fn func(chunk []any) error) error

ProcessFileChunked processes a large JSON file in chunks

type LazyJSON ΒΆ added in v1.2.0

type LazyJSON struct {
	// contains filtered or unexported fields
}

LazyJSON provides lazy parsing for JSON data The JSON is only parsed when a value is accessed

func NewLazyJSON ΒΆ added in v1.2.0

func NewLazyJSON(data []byte) *LazyJSON

NewLazyJSON creates a new LazyJSON from raw bytes

func (*LazyJSON) Error ΒΆ added in v1.2.0

func (lj *LazyJSON) Error() error

Error returns any parsing error

func (*LazyJSON) Get ΒΆ added in v1.2.0

func (lj *LazyJSON) Get(path string) (any, error)

Get retrieves a value at the specified path Parses the JSON on first access

func (*LazyJSON) IsParsed ΒΆ added in v1.2.0

func (lj *LazyJSON) IsParsed() bool

IsParsed returns true if the JSON has been parsed

func (*LazyJSON) Parse ΒΆ added in v1.2.0

func (lj *LazyJSON) Parse() (any, error)

Parse forces parsing and returns the parsed data

func (*LazyJSON) Parsed ΒΆ added in v1.2.0

func (lj *LazyJSON) Parsed() any

Parsed returns the parsed data without forcing parsing Returns nil if not yet parsed

func (*LazyJSON) Raw ΒΆ added in v1.2.0

func (lj *LazyJSON) Raw() []byte

Raw returns the raw JSON bytes

type LazyJSONDecoder ΒΆ added in v1.2.0

type LazyJSONDecoder struct {
	// contains filtered or unexported fields
}

LazyJSONDecoder provides lazy parsing for nested structures

func NewLazyJSONDecoder ΒΆ added in v1.2.0

func NewLazyJSONDecoder(data []byte) *LazyJSONDecoder

NewLazyJSONDecoder creates a lazy JSON decoder

func (*LazyJSONDecoder) GetPath ΒΆ added in v1.2.0

func (l *LazyJSONDecoder) GetPath(path string) (any, error)

GetPath gets a value at the specified path with lazy parsing

func (*LazyJSONDecoder) Parse ΒΆ added in v1.2.0

func (l *LazyJSONDecoder) Parse() (any, error)

Parse parses the JSON data if not already parsed

func (*LazyJSONDecoder) Raw ΒΆ added in v1.2.0

func (l *LazyJSONDecoder) Raw() []byte

Raw returns the raw JSON bytes

type LazyParser ΒΆ added in v1.2.0

type LazyParser struct {
	// contains filtered or unexported fields
}

LazyParser provides lazy JSON parsing that supports both JSON objects and arrays

func NewLazyParser ΒΆ added in v1.2.0

func NewLazyParser(data []byte) *LazyParser

NewLazyParser creates a new lazy parser

func (*LazyParser) Get ΒΆ added in v1.2.0

func (lp *LazyParser) Get(path string) (any, error)

Get retrieves a value at the given path

func (*LazyParser) GetAll ΒΆ added in v1.2.0

func (lp *LazyParser) GetAll() (map[string]any, error)

GetAll returns all parsed data as an interface Deprecated: Use GetValue() for better type support

func (*LazyParser) GetValue ΒΆ added in v1.2.2

func (lp *LazyParser) GetValue() (any, error)

GetValue returns all parsed data as interface{} (supports any JSON type)

func (*LazyParser) IsArray ΒΆ added in v1.2.2

func (lp *LazyParser) IsArray() bool

IsArray returns true if the parsed JSON is an array

func (*LazyParser) IsObject ΒΆ added in v1.2.2

func (lp *LazyParser) IsObject() bool

IsObject returns true if the parsed JSON is an object

func (*LazyParser) IsParsed ΒΆ added in v1.2.0

func (lp *LazyParser) IsParsed() bool

IsParsed returns whether the JSON has been parsed

func (*LazyParser) Raw ΒΆ added in v1.2.0

func (lp *LazyParser) Raw() []byte

Raw returns the raw JSON bytes

type Marshaler ΒΆ

type Marshaler interface {
	MarshalJSON() ([]byte, error)
}

Marshaler is the interface implemented by types that can marshal themselves into valid JSON.

type MarshalerError ΒΆ

type MarshalerError struct {
	Type reflect.Type
	Err  error
	// contains filtered or unexported fields
}

MarshalerError represents an error from calling a MarshalJSON or MarshalText method.

func (*MarshalerError) Error ΒΆ

func (e *MarshalerError) Error() string

func (*MarshalerError) Unwrap ΒΆ

func (e *MarshalerError) Unwrap() error

type MemoryTracker ΒΆ

type MemoryTracker struct {
	// contains filtered or unexported fields
}

MemoryTracker tracks memory usage during tests

func NewMemoryTracker ΒΆ

func NewMemoryTracker(name string) *MemoryTracker

NewMemoryTracker creates a new memory tracker

func (*MemoryTracker) Report ΒΆ

func (mt *MemoryTracker) Report(t *testing.T)

Report reports memory usage

type NDJSONProcessor ΒΆ added in v1.2.0

type NDJSONProcessor struct {
	// contains filtered or unexported fields
}

NDJSONProcessor processes newline-delimited JSON files

func NewNDJSONProcessor ΒΆ added in v1.2.0

func NewNDJSONProcessor(bufferSize int) *NDJSONProcessor

NewNDJSONProcessor creates a new NDJSON processor

func (*NDJSONProcessor) ProcessFile ΒΆ added in v1.2.0

func (np *NDJSONProcessor) ProcessFile(filename string, fn func(lineNum int, obj map[string]any) error) error

ProcessFile processes an NDJSON file line by line

func (*NDJSONProcessor) ProcessReader ΒΆ added in v1.2.0

func (np *NDJSONProcessor) ProcessReader(reader io.Reader, fn func(lineNum int, obj map[string]any) error) error

ProcessReader processes NDJSON from a reader

type Number ΒΆ

type Number string

Number represents a JSON number literal.

func (Number) Float64 ΒΆ

func (n Number) Float64() (float64, error)

Float64 returns the number as a float64.

func (Number) Int64 ΒΆ

func (n Number) Int64() (int64, error)

Int64 returns the number as an int64.

func (Number) String ΒΆ

func (n Number) String() string

String returns the literal text of the number.

type NumberPreservingDecoder ΒΆ

type NumberPreservingDecoder struct {
	// contains filtered or unexported fields
}

NumberPreservingDecoder provides JSON decoding with optimized number format preservation

func NewNumberPreservingDecoder ΒΆ

func NewNumberPreservingDecoder(preserveNumbers bool) *NumberPreservingDecoder

NewNumberPreservingDecoder creates a new decoder with performance and number preservation

func (*NumberPreservingDecoder) DecodeToAny ΒΆ

func (d *NumberPreservingDecoder) DecodeToAny(jsonStr string) (any, error)

DecodeToAny decodes JSON string to any type with performance and number preservation

type Operation ΒΆ

type Operation int

Operation represents the type of operation being performed

const (
	OpGet Operation = iota
	OpSet
	OpDelete
	OpValidate
)

func (Operation) String ΒΆ

func (op Operation) String() string

String returns the string representation of the operation

type OperationContext ΒΆ

type OperationContext struct {
	Context     context.Context
	Operation   Operation
	Path        string
	Value       any
	Options     *ProcessorOptions
	StartTime   time.Time
	CreatePaths bool
}

OperationContext contains context information for operations

type ParallelIterator ΒΆ added in v1.2.0

type ParallelIterator struct {
	// contains filtered or unexported fields
}

ParallelIterator processes arrays in parallel using worker goroutines

func NewParallelIterator ΒΆ added in v1.2.0

func NewParallelIterator(data []any, workers int) *ParallelIterator

NewParallelIterator creates a new parallel iterator

func (*ParallelIterator) Filter ΒΆ added in v1.2.0

func (it *ParallelIterator) Filter(predicate func(int, any) bool) []any

Filter filters elements in parallel using a predicate function Returns a new slice with elements that pass the predicate

func (*ParallelIterator) ForEach ΒΆ added in v1.2.0

func (it *ParallelIterator) ForEach(fn func(int, any) error) error

ForEach processes each element in parallel using the provided function The function receives the index and value of each element Returns the first error encountered, or nil if all operations succeed

func (*ParallelIterator) ForEachBatch ΒΆ added in v1.2.0

func (it *ParallelIterator) ForEachBatch(batchSize int, fn func(int, []any) error) error

ForEachBatch processes elements in batches in parallel Each batch is processed by a single goroutine

func (*ParallelIterator) Map ΒΆ added in v1.2.0

func (it *ParallelIterator) Map(transform func(int, any) (any, error)) ([]any, error)

Map applies a transformation function to each element in parallel Returns a new slice with the transformed values

type ParsedJSON ΒΆ added in v1.2.0

type ParsedJSON struct {
	// contains filtered or unexported fields
}

ParsedJSON represents a pre-parsed JSON document that can be reused for multiple operations. This is a performance optimization for scenarios where the same JSON is queried multiple times. OPTIMIZED: Pre-parsing avoids repeated JSON parsing overhead for repeated queries.

func (*ParsedJSON) Data ΒΆ added in v1.2.0

func (p *ParsedJSON) Data() any

Data returns the underlying parsed data

type PathInfo ΒΆ

type PathInfo struct {
	Segments     []PathSegment `json:"segments"`
	IsPointer    bool          `json:"is_pointer"`
	OriginalPath string        `json:"original_path"`
}

PathInfo contains parsed path information

type PathSegment ΒΆ

type PathSegment = internal.PathSegment

PathSegment represents a parsed path segment with its type and value

type PathType ΒΆ added in v1.2.0

type PathType int

PathType represents the complexity level of a path

const (
	// PathTypeSimple indicates a single key with no dots or brackets
	PathTypeSimple PathType = iota
	// PathTypeComplex indicates a path containing dots or brackets
	PathTypeComplex
)

func GetPathType ΒΆ added in v1.2.0

func GetPathType(path string) PathType

GetPathType determines if a path is simple or complex Simple paths are single keys with no dots or brackets

type PooledMapIterator ΒΆ added in v1.2.0

type PooledMapIterator struct {
	// contains filtered or unexported fields
}

PooledMapIterator uses pooled slices for efficient map iteration

func NewPooledMapIterator ΒΆ added in v1.2.0

func NewPooledMapIterator(m map[string]any) *PooledMapIterator

NewPooledMapIterator creates a pooled map iterator

func (*PooledMapIterator) Key ΒΆ added in v1.2.0

func (it *PooledMapIterator) Key() string

Key returns the current key

func (*PooledMapIterator) Next ΒΆ added in v1.2.0

func (it *PooledMapIterator) Next() bool

Next advances to the next key-value pair

func (*PooledMapIterator) Release ΒΆ added in v1.2.0

func (it *PooledMapIterator) Release()

Release returns the iterator to the pool

func (*PooledMapIterator) Value ΒΆ added in v1.2.0

func (it *PooledMapIterator) Value() any

Value returns the current value

type PooledSliceIterator ΒΆ added in v1.2.0

type PooledSliceIterator struct {
	// contains filtered or unexported fields
}

PooledSliceIterator uses pooled slices for efficient array iteration

func NewPooledSliceIterator ΒΆ added in v1.2.0

func NewPooledSliceIterator(data []any) *PooledSliceIterator

NewPooledSliceIterator creates a pooled slice iterator

func (*PooledSliceIterator) Index ΒΆ added in v1.2.0

func (it *PooledSliceIterator) Index() int

Index returns the current index

func (*PooledSliceIterator) Next ΒΆ added in v1.2.0

func (it *PooledSliceIterator) Next() bool

Next advances to the next element

func (*PooledSliceIterator) Release ΒΆ added in v1.2.0

func (it *PooledSliceIterator) Release()

Release returns the iterator to the pool

func (*PooledSliceIterator) Value ΒΆ added in v1.2.0

func (it *PooledSliceIterator) Value() any

Value returns the current element

type Processor ΒΆ

type Processor struct {
	// contains filtered or unexported fields
}

Processor is the main JSON processing engine with thread safety and performance optimization

func New ΒΆ

func New(config ...*Config) *Processor

New creates a new JSON processor with optimized configuration. If no configuration is provided, uses default configuration. This function follows the explicit config pattern as required by the design guidelines.

func (*Processor) BatchDeleteOptimized ΒΆ added in v1.2.0

func (p *Processor) BatchDeleteOptimized(jsonStr string, paths []string) (string, error)

BatchDeleteOptimized performs multiple Delete operations efficiently

func (*Processor) BatchSetOptimized ΒΆ added in v1.2.0

func (p *Processor) BatchSetOptimized(jsonStr string, updates map[string]any) (string, error)

BatchSetOptimized performs multiple Set operations efficiently

func (*Processor) ClearCache ΒΆ

func (p *Processor) ClearCache()

ClearCache clears all cached data

func (*Processor) Close ΒΆ

func (p *Processor) Close() error

Close closes the processor and cleans up resources This method is idempotent and thread-safe

func (*Processor) Compact ΒΆ

func (p *Processor) Compact(jsonStr string, opts ...*ProcessorOptions) (string, error)

Compact removes whitespace from JSON string

func (*Processor) CompactBuffer ΒΆ added in v1.1.0

func (p *Processor) CompactBuffer(dst *bytes.Buffer, src []byte, opts ...*ProcessorOptions) error

CompactBuffer appends to dst the JSON-encoded src with insignificant space characters elided. Compatible with encoding/json.Compact with optional ProcessorOptions support.

func (*Processor) CompilePath ΒΆ added in v1.2.0

func (p *Processor) CompilePath(path string) (*internal.CompiledPath, error)

CompilePath compiles a JSON path string into a CompiledPath for fast repeated operations The returned CompiledPath can be reused for multiple Get/Set/Delete operations

func (*Processor) Delete ΒΆ

func (p *Processor) Delete(jsonStr, path string, opts ...*ProcessorOptions) (string, error)

Delete removes a value from JSON at the specified path

func (*Processor) DeleteWithCleanNull ΒΆ added in v1.1.0

func (p *Processor) DeleteWithCleanNull(jsonStr, path string, opts ...*ProcessorOptions) (string, error)

DeleteWithCleanNull removes a value from JSON and cleans up null values Returns:

  • On success: modified JSON string and nil error
  • On failure: original unmodified JSON string and error information

func (*Processor) Encode ΒΆ added in v1.1.0

func (p *Processor) Encode(value any, config ...*EncodeConfig) (string, error)

Encode converts any Go value to JSON string This is a convenience method that matches the package-level Encode signature

func (*Processor) EncodeBatch ΒΆ

func (p *Processor) EncodeBatch(pairs map[string]any, pretty bool, opts ...*ProcessorOptions) (string, error)

EncodeBatch encodes multiple key-value pairs as a JSON object

func (*Processor) EncodeFields ΒΆ

func (p *Processor) EncodeFields(value any, fields []string, pretty bool, opts ...*ProcessorOptions) (string, error)

EncodeFields encodes struct fields selectively based on field names

func (*Processor) EncodePretty ΒΆ added in v1.1.0

func (p *Processor) EncodePretty(value any, config ...*EncodeConfig) (string, error)

EncodePretty converts any Go value to pretty-formatted JSON string This is a convenience method that matches the package-level EncodePretty signature

func (*Processor) EncodeStream ΒΆ

func (p *Processor) EncodeStream(values any, pretty bool, opts ...*ProcessorOptions) (string, error)

EncodeStream encodes multiple values as a JSON array stream

func (*Processor) EncodeStreamWithOptions ΒΆ

func (p *Processor) EncodeStreamWithOptions(values any, encOpts *EncodeConfig, opts ...*ProcessorOptions) (string, error)

EncodeStreamWithOptions encodes multiple values as a JSON array stream with advanced options

func (*Processor) EncodeWithConfig ΒΆ

func (p *Processor) EncodeWithConfig(value any, config *EncodeConfig, opts ...*ProcessorOptions) (string, error)

EncodeWithConfig converts any Go value to JSON string with full configuration control

func (*Processor) EncodeWithOptions ΒΆ

func (p *Processor) EncodeWithOptions(value any, encOpts *EncodeConfig, opts ...*ProcessorOptions) (string, error)

EncodeWithOptions converts any Go value to JSON string with advanced options

func (*Processor) FastDelete ΒΆ added in v1.2.0

func (p *Processor) FastDelete(jsonStr, path string) (string, error)

FastDelete is an optimized Delete operation for simple paths

func (*Processor) FastGetMultiple ΒΆ added in v1.2.0

func (p *Processor) FastGetMultiple(jsonStr string, paths []string) (map[string]any, error)

FastGetMultiple performs multiple Get operations with single parse

func (*Processor) FastSet ΒΆ added in v1.2.0

func (p *Processor) FastSet(jsonStr, path string, value any) (string, error)

FastSet is an optimized Set operation for simple paths Uses pooled resources and optimized marshaling

func (*Processor) Foreach ΒΆ

func (p *Processor) Foreach(jsonStr string, fn func(key any, item *IterableValue))

Foreach iterates over JSON arrays or objects using this processor

func (*Processor) ForeachNested ΒΆ added in v1.0.9

func (p *Processor) ForeachNested(jsonStr string, fn func(key any, item *IterableValue))

ForeachNested recursively iterates over all nested JSON structures This method traverses through all nested objects and arrays

func (*Processor) ForeachReturn ΒΆ

func (p *Processor) ForeachReturn(jsonStr string, fn func(key any, item *IterableValue)) (string, error)

ForeachReturn iterates over JSON arrays or objects and returns the JSON string This is useful for iteration with transformation purposes

func (*Processor) ForeachWithPath ΒΆ

func (p *Processor) ForeachWithPath(jsonStr, path string, fn func(key any, item *IterableValue)) error

ForeachWithPath iterates over JSON arrays or objects at a specific path using this processor This allows using custom processor configurations (security limits, nesting depth, etc.)

func (*Processor) ForeachWithPathAndControl ΒΆ added in v1.0.9

func (p *Processor) ForeachWithPathAndControl(jsonStr, path string, fn func(key any, value any) IteratorControl) error

ForeachWithPathAndControl iterates with control over iteration flow

func (*Processor) ForeachWithPathAndIterator ΒΆ added in v1.0.9

func (p *Processor) ForeachWithPathAndIterator(jsonStr, path string, fn func(key any, item *IterableValue, currentPath string) IteratorControl) error

ForeachWithPathAndIterator iterates over JSON at a path with path information

func (*Processor) FormatCompact ΒΆ added in v1.1.0

func (p *Processor) FormatCompact(jsonStr string, opts ...*ProcessorOptions) (string, error)

FormatCompact removes whitespace from JSON string (alias for Compact)

func (*Processor) FormatPretty ΒΆ

func (p *Processor) FormatPretty(jsonStr string, opts ...*ProcessorOptions) (string, error)

FormatPretty formats JSON string with indentation

func (*Processor) Get ΒΆ

func (p *Processor) Get(jsonStr, path string, opts ...*ProcessorOptions) (any, error)

Get retrieves a value from JSON using a path expression with performance

func (*Processor) GetArray ΒΆ added in v1.1.0

func (p *Processor) GetArray(jsonStr, path string, opts ...*ProcessorOptions) ([]any, error)

GetArray retrieves an array value from JSON at the specified path

func (*Processor) GetArrayWithDefault ΒΆ added in v1.1.0

func (p *Processor) GetArrayWithDefault(jsonStr, path string, defaultValue []any, opts ...*ProcessorOptions) []any

GetArrayWithDefault retrieves an array value from JSON with a default fallback

func (*Processor) GetBool ΒΆ added in v1.1.0

func (p *Processor) GetBool(jsonStr, path string, opts ...*ProcessorOptions) (bool, error)

GetBool retrieves a bool value from JSON at the specified path

func (*Processor) GetBoolWithDefault ΒΆ added in v1.1.0

func (p *Processor) GetBoolWithDefault(jsonStr, path string, defaultValue bool, opts ...*ProcessorOptions) bool

GetBoolWithDefault retrieves a bool value from JSON with a default fallback

func (*Processor) GetCompiled ΒΆ added in v1.2.0

func (p *Processor) GetCompiled(jsonStr string, cp *internal.CompiledPath) (any, error)

GetCompiled retrieves a value from JSON using a pre-compiled path PERFORMANCE: Skips path parsing for faster repeated operations

func (*Processor) GetCompiledExists ΒΆ added in v1.2.0

func (p *Processor) GetCompiledExists(data any, cp *internal.CompiledPath) bool

GetCompiledExists checks if a path exists in pre-parsed JSON data using a compiled path

func (*Processor) GetCompiledFromParsed ΒΆ added in v1.2.0

func (p *Processor) GetCompiledFromParsed(data any, cp *internal.CompiledPath) (any, error)

GetCompiledFromParsed retrieves a value from pre-parsed JSON data using a compiled path PERFORMANCE: No JSON parsing overhead - uses already parsed data

func (*Processor) GetConfig ΒΆ

func (p *Processor) GetConfig() *Config

GetConfig returns a copy of the processor configuration

func (*Processor) GetFloat64 ΒΆ added in v1.1.0

func (p *Processor) GetFloat64(jsonStr, path string, opts ...*ProcessorOptions) (float64, error)

GetFloat64 retrieves a float64 value from JSON at the specified path

func (*Processor) GetFloat64WithDefault ΒΆ added in v1.1.0

func (p *Processor) GetFloat64WithDefault(jsonStr, path string, defaultValue float64, opts ...*ProcessorOptions) float64

GetFloat64WithDefault retrieves a float64 value from JSON with a default fallback

func (*Processor) GetFromParsed ΒΆ added in v1.2.0

func (p *Processor) GetFromParsed(parsed *ParsedJSON, path string, opts ...*ProcessorOptions) (any, error)

GetFromParsed retrieves a value from a pre-parsed JSON document at the specified path. This is significantly faster than Get() for repeated queries on the same JSON.

OPTIMIZED: Skips JSON parsing, goes directly to path navigation.

func (*Processor) GetFromParsedData ΒΆ added in v1.2.0

func (p *Processor) GetFromParsedData(data any, path string) (any, error)

GetFromParsedData retrieves a value from already-parsed data Uses the processor's path navigation without re-parsing

func (*Processor) GetHealthStatus ΒΆ

func (p *Processor) GetHealthStatus() HealthStatus

GetHealthStatus returns the current health status

func (*Processor) GetInt ΒΆ added in v1.1.0

func (p *Processor) GetInt(jsonStr, path string, opts ...*ProcessorOptions) (int, error)

GetInt retrieves an int value from JSON at the specified path

func (*Processor) GetIntWithDefault ΒΆ added in v1.1.0

func (p *Processor) GetIntWithDefault(jsonStr, path string, defaultValue int, opts ...*ProcessorOptions) int

GetIntWithDefault retrieves an int value from JSON with a default fallback

func (*Processor) GetMultiple ΒΆ

func (p *Processor) GetMultiple(jsonStr string, paths []string, opts ...*ProcessorOptions) (map[string]any, error)

GetMultiple retrieves multiple values from JSON using multiple path expressions

func (*Processor) GetObject ΒΆ added in v1.1.0

func (p *Processor) GetObject(jsonStr, path string, opts ...*ProcessorOptions) (map[string]any, error)

GetObject retrieves an object value from JSON at the specified path

func (*Processor) GetObjectWithDefault ΒΆ added in v1.1.0

func (p *Processor) GetObjectWithDefault(jsonStr, path string, defaultValue map[string]any, opts ...*ProcessorOptions) map[string]any

GetObjectWithDefault retrieves an object value from JSON with a default fallback

func (*Processor) GetStats ΒΆ

func (p *Processor) GetStats() Stats

GetStats returns processor performance statistics

func (*Processor) GetString ΒΆ added in v1.1.0

func (p *Processor) GetString(jsonStr, path string, opts ...*ProcessorOptions) (string, error)

GetString retrieves a string value from JSON at the specified path

func (*Processor) GetStringWithDefault ΒΆ added in v1.1.0

func (p *Processor) GetStringWithDefault(jsonStr, path, defaultValue string, opts ...*ProcessorOptions) string

GetStringWithDefault retrieves a string value from JSON with a default fallback

func (*Processor) GetWithDefault ΒΆ added in v1.1.0

func (p *Processor) GetWithDefault(jsonStr, path string, defaultValue any, opts ...*ProcessorOptions) any

GetWithDefault retrieves a value from JSON with a default fallback

func (*Processor) HTMLEscapeBuffer ΒΆ added in v1.1.0

func (p *Processor) HTMLEscapeBuffer(dst *bytes.Buffer, src []byte, opts ...*ProcessorOptions)

HTMLEscapeBuffer appends to dst the JSON-encoded src with HTML-safe escaping. Replaces &, <, and > with \u0026, \u003c, and \u003e for safe HTML embedding. Compatible with encoding/json.HTMLEscape with optional ProcessorOptions support.

func (*Processor) IndentBuffer ΒΆ added in v1.1.0

func (p *Processor) IndentBuffer(dst *bytes.Buffer, src []byte, prefix, indent string, opts ...*ProcessorOptions) error

IndentBuffer appends to dst an indented form of the JSON-encoded src. Compatible with encoding/json.Indent with optional ProcessorOptions support.

func (*Processor) IsClosed ΒΆ

func (p *Processor) IsClosed() bool

IsClosed returns true if the processor has been closed

func (*Processor) LoadFromFile ΒΆ

func (p *Processor) LoadFromFile(filePath string, opts ...*ProcessorOptions) (string, error)

LoadFromFile loads JSON data from a file and returns the raw JSON string.

func (*Processor) LoadFromFileAsData ΒΆ added in v1.1.0

func (p *Processor) LoadFromFileAsData(filePath string, opts ...*ProcessorOptions) (any, error)

LoadFromFileAsData loads JSON data from a file and returns the parsed data structure.

func (*Processor) LoadFromReader ΒΆ

func (p *Processor) LoadFromReader(reader io.Reader, opts ...*ProcessorOptions) (string, error)

LoadFromReader loads JSON data from an io.Reader and returns the raw JSON string.

func (*Processor) LoadFromReaderAsData ΒΆ added in v1.1.0

func (p *Processor) LoadFromReaderAsData(reader io.Reader, opts ...*ProcessorOptions) (any, error)

LoadFromReaderAsData loads JSON data from an io.Reader and returns the parsed data structure.

func (*Processor) Marshal ΒΆ

func (p *Processor) Marshal(value any, opts ...*ProcessorOptions) ([]byte, error)

Marshal converts any Go value to JSON bytes (similar to json.Marshal)

func (*Processor) MarshalIndent ΒΆ

func (p *Processor) MarshalIndent(value any, prefix, indent string, opts ...*ProcessorOptions) ([]byte, error)

MarshalIndent converts any Go value to indented JSON bytes (similar to json.MarshalIndent)

func (*Processor) MarshalToFile ΒΆ added in v1.0.6

func (p *Processor) MarshalToFile(path string, data any, pretty ...bool) error

MarshalToFile converts data to JSON and saves it to the specified file.

func (*Processor) Parse ΒΆ

func (p *Processor) Parse(jsonStr string, target any, opts ...*ProcessorOptions) error

Parse parses a JSON string into the provided target with improved error handling

func (*Processor) PreParse ΒΆ added in v1.2.0

func (p *Processor) PreParse(jsonStr string, opts ...*ProcessorOptions) (*ParsedJSON, error)

PreParse parses a JSON string and returns a ParsedJSON object that can be reused for multiple Get operations. This is a performance optimization for scenarios where the same JSON is queried multiple times.

OPTIMIZED: Pre-parsing avoids repeated JSON parsing overhead for repeated queries.

Example:

parsed, err := processor.PreParse(jsonStr)
if err != nil { return err }
value1, _ := processor.GetFromParsed(parsed, "path1")
value2, _ := processor.GetFromParsed(parsed, "path2")

func (*Processor) ProcessBatch ΒΆ

func (p *Processor) ProcessBatch(operations []BatchOperation, opts ...*ProcessorOptions) ([]BatchResult, error)

ProcessBatch processes multiple operations in a single batch

func (*Processor) SafeGet ΒΆ

func (p *Processor) SafeGet(jsonStr, path string) TypeSafeAccessResult

SafeGet performs a type-safe get operation with comprehensive error handling

func (*Processor) SaveToFile ΒΆ

func (p *Processor) SaveToFile(filePath string, data any, pretty ...bool) error

SaveToFile saves data to a JSON file with automatic directory creation

func (*Processor) SaveToWriter ΒΆ

func (p *Processor) SaveToWriter(writer io.Writer, data any, pretty bool, opts ...*ProcessorOptions) error

SaveToWriter saves data to an io.Writer

func (*Processor) Set ΒΆ

func (p *Processor) Set(jsonStr, path string, value any, opts ...*ProcessorOptions) (string, error)

Set sets a value in JSON at the specified path Returns:

  • On success: modified JSON string and nil error
  • On failure: original unmodified JSON string and error information

func (*Processor) SetFromParsed ΒΆ added in v1.2.0

func (p *Processor) SetFromParsed(parsed *ParsedJSON, path string, value any, opts ...*ProcessorOptions) (*ParsedJSON, error)

SetFromParsed modifies a pre-parsed JSON document at the specified path. Returns a new ParsedJSON with the modified data (original is not modified).

OPTIMIZED: Skips JSON parsing, works directly on parsed data.

func (*Processor) SetLogger ΒΆ

func (p *Processor) SetLogger(logger *slog.Logger)

SetLogger sets a custom structured logger for the processor

func (*Processor) SetMultiple ΒΆ

func (p *Processor) SetMultiple(jsonStr string, updates map[string]any, opts ...*ProcessorOptions) (string, error)

SetMultiple sets multiple values in JSON using a map of path-value pairs Returns:

  • On success: modified JSON string and nil error
  • On failure: original unmodified JSON string and error information

func (*Processor) SetMultipleWithAdd ΒΆ added in v1.1.0

func (p *Processor) SetMultipleWithAdd(jsonStr string, updates map[string]any, opts ...*ProcessorOptions) (string, error)

SetMultipleWithAdd sets multiple values with automatic path creation Returns:

  • On success: modified JSON string and nil error
  • On failure: original unmodified JSON string and error information

func (*Processor) SetWithAdd ΒΆ added in v1.1.0

func (p *Processor) SetWithAdd(jsonStr, path string, value any, opts ...*ProcessorOptions) (string, error)

SetWithAdd sets a value with automatic path creation Returns:

  • On success: modified JSON string and nil error
  • On failure: original unmodified JSON string and error information

func (*Processor) ToJsonString ΒΆ

func (p *Processor) ToJsonString(value any, opts ...*ProcessorOptions) (string, error)

ToJsonString converts any Go value to JSON string with HTML escaping (safe for web)

func (*Processor) ToJsonStringPretty ΒΆ

func (p *Processor) ToJsonStringPretty(value any, opts ...*ProcessorOptions) (string, error)

ToJsonStringPretty converts any Go value to pretty JSON string with HTML escaping

func (*Processor) ToJsonStringStandard ΒΆ

func (p *Processor) ToJsonStringStandard(value any, opts ...*ProcessorOptions) (string, error)

ToJsonStringStandard converts any Go value to compact JSON string without HTML escaping

func (*Processor) Unmarshal ΒΆ

func (p *Processor) Unmarshal(data []byte, v any, opts ...*ProcessorOptions) error

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. This method is fully compatible with encoding/json.Unmarshal.

func (*Processor) UnmarshalFromFile ΒΆ added in v1.0.6

func (p *Processor) UnmarshalFromFile(path string, v any, opts ...*ProcessorOptions) error

UnmarshalFromFile reads JSON data from the specified file and unmarshals it into the provided value.

func (*Processor) Valid ΒΆ

func (p *Processor) Valid(jsonStr string, opts ...*ProcessorOptions) (bool, error)

Valid validates JSON format without parsing the entire structure

func (*Processor) ValidBytes ΒΆ added in v1.1.0

func (p *Processor) ValidBytes(data []byte) bool

ValidBytes validates JSON format from byte slice (matches encoding/json.Valid signature) This method provides compatibility with the standard library's json.Valid function

func (*Processor) ValidateSchema ΒΆ

func (p *Processor) ValidateSchema(jsonStr string, schema *Schema, opts ...*ProcessorOptions) ([]ValidationError, error)

ValidateSchema validates JSON data against a schema

func (*Processor) WarmupCache ΒΆ

func (p *Processor) WarmupCache(jsonStr string, paths []string, opts ...*ProcessorOptions) (*WarmupResult, error)

WarmupCache pre-loads commonly used paths into cache to improve first-access performance

type ProcessorMetrics ΒΆ

type ProcessorMetrics struct {
	TotalOperations       int64         `json:"total_operations"`
	SuccessfulOperations  int64         `json:"successful_operations"`
	FailedOperations      int64         `json:"failed_operations"`
	SuccessRate           float64       `json:"success_rate"`
	CacheHits             int64         `json:"cache_hits"`
	CacheMisses           int64         `json:"cache_misses"`
	CacheHitRate          float64       `json:"cache_hit_rate"`
	AverageProcessingTime time.Duration `json:"average_processing_time"`
	MaxProcessingTime     time.Duration `json:"max_processing_time"`
	MinProcessingTime     time.Duration `json:"min_processing_time"`
	TotalMemoryAllocated  int64         `json:"total_memory_allocated"`
	PeakMemoryUsage       int64         `json:"peak_memory_usage"`
	CurrentMemoryUsage    int64         `json:"current_memory_usage"`
	ActiveConcurrentOps   int64         `json:"active_concurrent_ops"`
	MaxConcurrentOps      int64         `json:"max_concurrent_ops"`
	// contains filtered or unexported fields
}

ProcessorMetrics provides comprehensive processor performance metrics

type ProcessorOptions ΒΆ

type ProcessorOptions struct {
	Context         context.Context `json:"-"`
	CacheResults    bool            `json:"cache_results"`
	StrictMode      bool            `json:"strict_mode"`
	MaxDepth        int             `json:"max_depth"`
	AllowComments   bool            `json:"allow_comments"`
	PreserveNumbers bool            `json:"preserve_numbers"`
	CreatePaths     bool            `json:"create_paths"`
	CleanupNulls    bool            `json:"cleanup_nulls"`
	CompactArrays   bool            `json:"compact_arrays"`
	ContinueOnError bool            `json:"continue_on_error"`
	// OPTIMIZED: SkipValidation allows skipping security validation for trusted input
	// WARNING: Only use this option when you are certain the input is safe
	// Use with caution - skipping validation may expose security vulnerabilities
	SkipValidation bool `json:"skip_validation"`
}

ProcessorOptions provides per-operation configuration

func DefaultOptions ΒΆ

func DefaultOptions() *ProcessorOptions

DefaultOptions returns default processor options as a singleton. IMPORTANT: Returns an immutable pointer - callers MUST NOT modify the returned value. Modifying the returned value will affect all users of DefaultOptions(). Use DefaultOptionsClone() if you need a modifiable copy.

Example:

// Read-only access (safe):
opts := json.DefaultOptions()
if opts.MaxDepth > 10 { ... }

// Modification (use clone):
opts := json.DefaultOptionsClone()
opts.MaxDepth = 100

func DefaultOptionsClone ΒΆ added in v1.2.0

func DefaultOptionsClone() *ProcessorOptions

DefaultOptionsClone returns a modifiable copy of the default processor options. Use this when you need to customize the options before passing to operations.

func (*ProcessorOptions) Clone ΒΆ

func (opts *ProcessorOptions) Clone() *ProcessorOptions

Clone creates a deep copy of ProcessorOptions

type PropertyAccessResult ΒΆ

type PropertyAccessResult struct {
	Value  any
	Exists bool
	Path   string // Path that was accessed
	Error  error
}

PropertyAccessResult represents the result of a property access operation

type RecursiveProcessor ΒΆ

type RecursiveProcessor struct {
	// contains filtered or unexported fields
}

RecursiveProcessor implements true recursive processing for all operations

func NewRecursiveProcessor ΒΆ

func NewRecursiveProcessor(p *Processor) *RecursiveProcessor

NewRecursiveProcessor creates a new unified recursive processor

func (*RecursiveProcessor) ProcessRecursively ΒΆ

func (urp *RecursiveProcessor) ProcessRecursively(data any, path string, operation Operation, value any) (any, error)

ProcessRecursively performs recursive processing for any operation

func (*RecursiveProcessor) ProcessRecursivelyWithOptions ΒΆ

func (urp *RecursiveProcessor) ProcessRecursivelyWithOptions(data any, path string, operation Operation, value any, createPaths bool) (any, error)

ProcessRecursivelyWithOptions performs recursive processing with path creation options

type ResourceManagerStats ΒΆ added in v1.0.6

type ResourceManagerStats struct {
	AllocatedBuilders int64 `json:"allocated_builders"`
	AllocatedSegments int64 `json:"allocated_segments"`
	AllocatedBuffers  int64 `json:"allocated_buffers"`
	AllocatedOptions  int64 `json:"allocated_options"`
	AllocatedMaps     int64 `json:"allocated_maps"`
	LastCleanup       int64 `json:"last_cleanup"`
}

type ResourceMonitor ΒΆ

type ResourceMonitor struct {
	// contains filtered or unexported fields
}

ResourceMonitor provides resource monitoring and leak detection

func NewResourceMonitor ΒΆ

func NewResourceMonitor() *ResourceMonitor

NewResourceMonitor creates a new resource monitor

func (*ResourceMonitor) CheckForLeaks ΒΆ

func (rm *ResourceMonitor) CheckForLeaks() []string

CheckForLeaks checks for potential resource leaks

func (*ResourceMonitor) GetMemoryEfficiency ΒΆ

func (rm *ResourceMonitor) GetMemoryEfficiency() float64

GetMemoryEfficiency returns the memory efficiency percentage

func (*ResourceMonitor) GetPoolEfficiency ΒΆ

func (rm *ResourceMonitor) GetPoolEfficiency() float64

GetPoolEfficiency returns the pool efficiency percentage

func (*ResourceMonitor) GetStats ΒΆ

func (rm *ResourceMonitor) GetStats() ResourceStats

GetStats returns current resource statistics

func (*ResourceMonitor) RecordAllocation ΒΆ

func (rm *ResourceMonitor) RecordAllocation(bytes int64)

RecordAllocation records an allocation of the specified size

func (*ResourceMonitor) RecordDeallocation ΒΆ

func (rm *ResourceMonitor) RecordDeallocation(bytes int64)

RecordDeallocation records a deallocation of the specified size

func (*ResourceMonitor) RecordOperation ΒΆ

func (rm *ResourceMonitor) RecordOperation(duration time.Duration)

RecordOperation records an operation with its duration

func (*ResourceMonitor) RecordPoolEviction ΒΆ

func (rm *ResourceMonitor) RecordPoolEviction()

RecordPoolEviction records a pool eviction

func (*ResourceMonitor) RecordPoolHit ΒΆ

func (rm *ResourceMonitor) RecordPoolHit()

RecordPoolHit records a pool cache hit

func (*ResourceMonitor) RecordPoolMiss ΒΆ

func (rm *ResourceMonitor) RecordPoolMiss()

RecordPoolMiss records a pool cache miss

func (*ResourceMonitor) Reset ΒΆ

func (rm *ResourceMonitor) Reset()

Reset resets all resource statistics

type ResourcePoolStats ΒΆ

type ResourcePoolStats struct {
	StringBuilderPoolActive bool `json:"string_builder_pool_active"` // Whether string builder pool is active
	PathSegmentPoolActive   bool `json:"path_segment_pool_active"`   // Whether path segment pool is active
}

ResourcePoolStats provides statistics about resource pools

type ResourceStats ΒΆ

type ResourceStats struct {
	AllocatedBytes    int64         `json:"allocated_bytes"`
	FreedBytes        int64         `json:"freed_bytes"`
	PeakMemoryUsage   int64         `json:"peak_memory_usage"`
	PoolHits          int64         `json:"pool_hits"`
	PoolMisses        int64         `json:"pool_misses"`
	PoolEvictions     int64         `json:"pool_evictions"`
	MaxGoroutines     int64         `json:"max_goroutines"`
	CurrentGoroutines int64         `json:"current_goroutines"`
	AvgResponseTime   time.Duration `json:"avg_response_time"`
	TotalOperations   int64         `json:"total_operations"`
}

ResourceStats represents resource usage statistics

type RootDataTypeConversionError ΒΆ

type RootDataTypeConversionError struct {
	RequiredType string
	RequiredSize int
	CurrentType  string
}

RootDataTypeConversionError signals that root data type conversion is needed

func (*RootDataTypeConversionError) Error ΒΆ

type SamplingReader ΒΆ added in v1.2.0

type SamplingReader struct {
	// contains filtered or unexported fields
}

SamplingReader samples data from large JSON arrays

func NewSamplingReader ΒΆ added in v1.2.0

func NewSamplingReader(reader io.Reader, sampleSize int) *SamplingReader

NewSamplingReader creates a new sampling reader

func (*SamplingReader) Sample ΒΆ added in v1.2.0

func (sr *SamplingReader) Sample(fn func(index int, item any) bool) error

Sample reads a sample of items from a JSON array

func (*SamplingReader) TotalRead ΒΆ added in v1.2.0

func (sr *SamplingReader) TotalRead() int64

TotalRead returns the total number of items read

type Schema ΒΆ

type Schema struct {
	Type                 string             `json:"type,omitempty"`
	Properties           map[string]*Schema `json:"properties,omitempty"`
	Items                *Schema            `json:"items,omitempty"`
	Required             []string           `json:"required,omitempty"`
	MinLength            int                `json:"minLength,omitempty"`
	MaxLength            int                `json:"maxLength,omitempty"`
	Minimum              float64            `json:"minimum,omitempty"`
	Maximum              float64            `json:"maximum,omitempty"`
	Pattern              string             `json:"pattern,omitempty"`
	Format               string             `json:"format,omitempty"`
	AdditionalProperties bool               `json:"additionalProperties,omitempty"`
	MinItems             int                `json:"minItems,omitempty"`
	MaxItems             int                `json:"maxItems,omitempty"`
	UniqueItems          bool               `json:"uniqueItems,omitempty"`
	Enum                 []any              `json:"enum,omitempty"`
	Const                any                `json:"const,omitempty"`
	MultipleOf           float64            `json:"multipleOf,omitempty"`
	ExclusiveMinimum     bool               `json:"exclusiveMinimum,omitempty"`
	ExclusiveMaximum     bool               `json:"exclusiveMaximum,omitempty"`
	Title                string             `json:"title,omitempty"`
	Description          string             `json:"description,omitempty"`
	Default              any                `json:"default,omitempty"`
	Examples             []any              `json:"examples,omitempty"`
	// contains filtered or unexported fields
}

Schema represents a JSON schema for validation

func DefaultSchema ΒΆ

func DefaultSchema() *Schema

DefaultSchema returns a default schema configuration

func (*Schema) HasMaxItems ΒΆ

func (s *Schema) HasMaxItems() bool

HasMaxItems returns true if MaxItems constraint is explicitly set

func (*Schema) HasMaxLength ΒΆ

func (s *Schema) HasMaxLength() bool

HasMaxLength returns true if MaxLength constraint is explicitly set

func (*Schema) HasMaximum ΒΆ

func (s *Schema) HasMaximum() bool

HasMaximum returns true if Maximum constraint is explicitly set

func (*Schema) HasMinItems ΒΆ

func (s *Schema) HasMinItems() bool

HasMinItems returns true if MinItems constraint is explicitly set

func (*Schema) HasMinLength ΒΆ

func (s *Schema) HasMinLength() bool

HasMinLength returns true if MinLength constraint is explicitly set

func (*Schema) HasMinimum ΒΆ

func (s *Schema) HasMinimum() bool

HasMinimum returns true if Minimum constraint is explicitly set

func (*Schema) SetExclusiveMaximum ΒΆ

func (s *Schema) SetExclusiveMaximum(exclusive bool) *Schema

SetExclusiveMaximum sets the exclusive maximum flag

func (*Schema) SetExclusiveMinimum ΒΆ

func (s *Schema) SetExclusiveMinimum(exclusive bool) *Schema

SetExclusiveMinimum sets the exclusive minimum flag

func (*Schema) SetMaxItems ΒΆ

func (s *Schema) SetMaxItems(maxItems int) *Schema

SetMaxItems sets the maximum items constraint for arrays

func (*Schema) SetMaxLength ΒΆ

func (s *Schema) SetMaxLength(maxLength int) *Schema

SetMaxLength sets the maximum length constraint

func (*Schema) SetMaximum ΒΆ

func (s *Schema) SetMaximum(maximum float64) *Schema

SetMaximum sets the maximum value constraint

func (*Schema) SetMinItems ΒΆ

func (s *Schema) SetMinItems(minItems int) *Schema

SetMinItems sets the minimum items constraint for arrays

func (*Schema) SetMinLength ΒΆ

func (s *Schema) SetMinLength(minLength int) *Schema

SetMinLength sets the minimum length constraint

func (*Schema) SetMinimum ΒΆ

func (s *Schema) SetMinimum(minimum float64) *Schema

SetMinimum sets the minimum value constraint

type SecurityValidator ΒΆ added in v1.0.6

type SecurityValidator struct {
	// contains filtered or unexported fields
}

SecurityValidator provides comprehensive security validation for JSON processing.

func NewSecurityValidator ΒΆ added in v1.0.6

func NewSecurityValidator(maxJSONSize int64, maxPathLength, maxNestingDepth int, fullSecurityScan bool) *SecurityValidator

NewSecurityValidator creates a new security validator with the given limits.

func (*SecurityValidator) ValidateAll ΒΆ added in v1.0.7

func (sv *SecurityValidator) ValidateAll(jsonStr, path string) error

ValidateAll performs comprehensive validation of both JSON and path inputs.

func (*SecurityValidator) ValidateJSONInput ΒΆ added in v1.0.6

func (sv *SecurityValidator) ValidateJSONInput(jsonStr string) error

ValidateJSONInput performs comprehensive JSON input validation with enhanced security. PERFORMANCE: Uses caching to avoid repeated validation of the same JSON string.

func (*SecurityValidator) ValidatePathInput ΒΆ added in v1.0.6

func (sv *SecurityValidator) ValidatePathInput(path string) error

ValidatePathInput performs comprehensive path validation with enhanced security.

type ShardStats ΒΆ

type ShardStats struct {
	Size   int64 `json:"size"`
	Memory int64 `json:"memory"`
}

ShardStats provides statistics for a single cache shard

type Stats ΒΆ

type Stats struct {
	CacheSize        int64         `json:"cache_size"`
	CacheMemory      int64         `json:"cache_memory"`
	MaxCacheSize     int           `json:"max_cache_size"`
	HitCount         int64         `json:"hit_count"`
	MissCount        int64         `json:"miss_count"`
	HitRatio         float64       `json:"hit_ratio"`
	CacheTTL         time.Duration `json:"cache_ttl"`
	CacheEnabled     bool          `json:"cache_enabled"`
	IsClosed         bool          `json:"is_closed"`
	MemoryEfficiency float64       `json:"memory_efficiency"`
	OperationCount   int64         `json:"operation_count"`
	ErrorCount       int64         `json:"error_count"`
}

Stats provides processor performance statistics

func GetStats ΒΆ added in v1.1.0

func GetStats() Stats

GetStats returns statistics about the default processor.

type StreamIterator ΒΆ added in v1.2.0

type StreamIterator struct {
	// contains filtered or unexported fields
}

StreamIterator provides memory-efficient iteration over large JSON arrays It processes elements one at a time without loading the entire array into memory

func NewStreamIterator ΒΆ added in v1.2.0

func NewStreamIterator(reader io.Reader) *StreamIterator

NewStreamIterator creates a stream iterator from a reader with default settings

func NewStreamIteratorWithConfig ΒΆ added in v1.2.0

func NewStreamIteratorWithConfig(reader io.Reader, config StreamIteratorConfig) *StreamIterator

NewStreamIteratorWithConfig creates a stream iterator with custom configuration PERFORMANCE: Configurable buffer size improves throughput for large JSON streams

func (*StreamIterator) Err ΒΆ added in v1.2.0

func (si *StreamIterator) Err() error

Err returns any error encountered during iteration

func (*StreamIterator) Index ΒΆ added in v1.2.0

func (si *StreamIterator) Index() int

Index returns the current index

func (*StreamIterator) Next ΒΆ added in v1.2.0

func (si *StreamIterator) Next() bool

Next advances to the next element Returns true if there is a next element, false otherwise

func (*StreamIterator) Value ΒΆ added in v1.2.0

func (si *StreamIterator) Value() any

Value returns the current element

type StreamIteratorConfig ΒΆ added in v1.2.0

type StreamIteratorConfig struct {
	BufferSize int  // Buffer size for underlying reader (default: 32KB)
	ReadAhead  bool // Enable read-ahead buffering for improved performance
}

StreamIteratorConfig holds configuration options for StreamIterator

type StreamObjectIterator ΒΆ added in v1.2.0

type StreamObjectIterator struct {
	// contains filtered or unexported fields
}

StreamObjectIterator provides memory-efficient iteration over JSON objects

func NewStreamObjectIterator ΒΆ added in v1.2.0

func NewStreamObjectIterator(reader io.Reader) *StreamObjectIterator

NewStreamObjectIterator creates a stream object iterator from a reader

func (*StreamObjectIterator) Err ΒΆ added in v1.2.0

func (soi *StreamObjectIterator) Err() error

Err returns any error encountered

func (*StreamObjectIterator) Key ΒΆ added in v1.2.0

func (soi *StreamObjectIterator) Key() string

Key returns the current key

func (*StreamObjectIterator) Next ΒΆ added in v1.2.0

func (soi *StreamObjectIterator) Next() bool

Next advances to the next key-value pair

func (*StreamObjectIterator) Value ΒΆ added in v1.2.0

func (soi *StreamObjectIterator) Value() any

Value returns the current value

type StreamingProcessor ΒΆ added in v1.2.0

type StreamingProcessor struct {
	// contains filtered or unexported fields
}

StreamingProcessor handles large JSON files efficiently

func NewStreamingProcessor ΒΆ added in v1.2.0

func NewStreamingProcessor(reader io.Reader, bufferSize int) *StreamingProcessor

NewStreamingProcessor creates a streaming processor for large JSON

func (*StreamingProcessor) GetStats ΒΆ added in v1.2.0

func (sp *StreamingProcessor) GetStats() StreamingStats

GetStats returns streaming statistics

func (*StreamingProcessor) StreamArray ΒΆ added in v1.2.0

func (sp *StreamingProcessor) StreamArray(fn func(index int, item any) bool) error

StreamArray streams array elements one at a time This is memory-efficient for large arrays

func (*StreamingProcessor) StreamArrayChunked ΒΆ added in v1.2.0

func (sp *StreamingProcessor) StreamArrayChunked(chunkSize int, fn func([]any) error) error

StreamArrayChunked streams array elements in chunks for memory-efficient processing The chunkSize parameter controls how many elements are processed at once

func (*StreamingProcessor) StreamObject ΒΆ added in v1.2.0

func (sp *StreamingProcessor) StreamObject(fn func(key string, value any) bool) error

StreamObject streams object key-value pairs

func (*StreamingProcessor) StreamObjectChunked ΒΆ added in v1.2.0

func (sp *StreamingProcessor) StreamObjectChunked(chunkSize int, fn func(map[string]any) error) error

StreamObjectChunked streams object key-value pairs in chunks for memory-efficient processing The chunkSize parameter controls how many pairs are processed at once

type StreamingStats ΒΆ added in v1.2.0

type StreamingStats struct {
	BytesProcessed int64
	ItemsProcessed int64
	Depth          int
}

StreamingStats tracks streaming processing statistics

type SyntaxError ΒΆ

type SyntaxError struct {
	Offset int64 // error occurred after reading Offset bytes
	// contains filtered or unexported fields
}

SyntaxError is a description of a JSON syntax error. Unmarshal will return a SyntaxError if the JSON can't be parsed.

func (*SyntaxError) Error ΒΆ

func (e *SyntaxError) Error() string

type TestDataGenerator ΒΆ

type TestDataGenerator struct {
	// contains filtered or unexported fields
}

TestDataGenerator generates test data for various scenarios

func NewTestDataGenerator ΒΆ

func NewTestDataGenerator() *TestDataGenerator

NewTestDataGenerator creates a new test data generator

func (*TestDataGenerator) GenerateArrayJSON ΒΆ

func (g *TestDataGenerator) GenerateArrayJSON() string

GenerateArrayJSON generates JSON with various array structures

func (*TestDataGenerator) GenerateComplexJSON ΒΆ

func (g *TestDataGenerator) GenerateComplexJSON() string

GenerateComplexJSON generates complex nested JSON structures

func (*TestDataGenerator) GenerateInvalidJSON ΒΆ

func (g *TestDataGenerator) GenerateInvalidJSON() []string

GenerateInvalidJSON generates invalid JSON for error testing

func (*TestDataGenerator) GenerateSimpleJSON ΒΆ

func (g *TestDataGenerator) GenerateSimpleJSON() string

GenerateSimpleJSON generates simple JSON structures

type TestHelper ΒΆ

type TestHelper struct {
	// contains filtered or unexported fields
}

TestHelper provides utilities for testing JSON operations

func NewTestHelper ΒΆ

func NewTestHelper(t *testing.T) *TestHelper

NewTestHelper creates a new test helper

func (*TestHelper) AssertEqual ΒΆ

func (h *TestHelper) AssertEqual(expected, actual any, msgAndArgs ...any)

AssertEqual checks if two values are equal

func (*TestHelper) AssertError ΒΆ

func (h *TestHelper) AssertError(err error, msgAndArgs ...any)

AssertError checks that error is not nil

func (*TestHelper) AssertErrorContains ΒΆ

func (h *TestHelper) AssertErrorContains(err error, contains string, msgAndArgs ...any)

AssertErrorContains checks that error contains specific text

func (*TestHelper) AssertFalse ΒΆ

func (h *TestHelper) AssertFalse(condition bool, msgAndArgs ...any)

AssertFalse checks that condition is false

func (*TestHelper) AssertNil ΒΆ

func (h *TestHelper) AssertNil(value any, msgAndArgs ...any)

AssertNil checks that value is nil

func (*TestHelper) AssertNoError ΒΆ

func (h *TestHelper) AssertNoError(err error, msgAndArgs ...any)

AssertNoError checks that error is nil

func (*TestHelper) AssertNoPanic ΒΆ

func (h *TestHelper) AssertNoPanic(fn func(), msgAndArgs ...any)

AssertNoPanic checks that function doesn't panic

func (*TestHelper) AssertNotEqual ΒΆ

func (h *TestHelper) AssertNotEqual(expected, actual any, msgAndArgs ...any)

AssertNotEqual checks if two values are not equal

func (*TestHelper) AssertNotNil ΒΆ

func (h *TestHelper) AssertNotNil(value any, msgAndArgs ...any)

AssertNotNil checks that value is not nil

func (*TestHelper) AssertPanic ΒΆ

func (h *TestHelper) AssertPanic(fn func(), msgAndArgs ...any)

AssertPanic checks that function panics

func (*TestHelper) AssertTrue ΒΆ

func (h *TestHelper) AssertTrue(condition bool, msgAndArgs ...any)

AssertTrue checks that condition is true

type TextMarshaler ΒΆ

type TextMarshaler interface {
	MarshalText() (text []byte, err error)
}

TextMarshaler is the interface implemented by an object that can marshal itself into a textual form.

MarshalText encodes the receiver into UTF-8-encoded text and returns the result.

type TextUnmarshaler ΒΆ

type TextUnmarshaler interface {
	UnmarshalText(text []byte) error
}

TextUnmarshaler is the interface implemented by an object that can unmarshal a textual representation of itself.

UnmarshalText must be able to decode the form generated by MarshalText. UnmarshalText must copy the text if it wishes to retain the text after returning.

type Token ΒΆ

type Token any

Token holds a value of one of these types:

Delim, for the four JSON delimiters [ ] { }
bool, for JSON booleans
float64, for JSON numbers
Number, for JSON numbers
string, for JSON string literals
nil, for JSON null

type TypeSafeAccessResult ΒΆ

type TypeSafeAccessResult struct {
	Value  any
	Exists bool
	Type   string
}

TypeSafeAccessResult represents the result of a type-safe access operation

func (TypeSafeAccessResult) AsBool ΒΆ

func (r TypeSafeAccessResult) AsBool() (bool, error)

AsBool safely converts the result to bool

func (TypeSafeAccessResult) AsFloat64 ΒΆ added in v1.2.0

func (r TypeSafeAccessResult) AsFloat64() (float64, error)

AsFloat64 safely converts the result to float64 with precision checks

func (TypeSafeAccessResult) AsInt ΒΆ

func (r TypeSafeAccessResult) AsInt() (int, error)

AsInt safely converts the result to int with overflow and precision checks

func (TypeSafeAccessResult) AsString ΒΆ

func (r TypeSafeAccessResult) AsString() (string, error)

AsString safely converts the result to string. Returns ErrTypeMismatch if the value is not a string type. Use AsStringConverted() for explicit type conversion with formatting.

func (TypeSafeAccessResult) AsStringConverted ΒΆ added in v1.2.0

func (r TypeSafeAccessResult) AsStringConverted() (string, error)

AsStringConverted converts the result to string using fmt.Sprintf formatting. Use this when you explicitly want string representation of any type. For strict type checking, use AsString() instead.

type TypeSafeResult ΒΆ

type TypeSafeResult[T any] struct {
	Value  T
	Exists bool
	Error  error
}

TypeSafeResult represents a type-safe operation result

func SafeGetTypedWithProcessor ΒΆ

func SafeGetTypedWithProcessor[T any](p *Processor, jsonStr, path string) TypeSafeResult[T]

SafeGetTypedWithProcessor performs a type-safe get operation with generic type constraints

func (TypeSafeResult[T]) Ok ΒΆ

func (r TypeSafeResult[T]) Ok() bool

Ok returns true if the result is valid (no error and exists)

func (TypeSafeResult[T]) Unwrap ΒΆ

func (r TypeSafeResult[T]) Unwrap() T

Unwrap returns the value or zero value if there's an error For panic behavior, use UnwrapOrPanic instead

func (TypeSafeResult[T]) UnwrapOr ΒΆ

func (r TypeSafeResult[T]) UnwrapOr(defaultValue T) T

UnwrapOr returns the value or the provided default if there's an error or value doesn't exist

func (TypeSafeResult[T]) UnwrapOrPanic ΒΆ added in v1.0.4

func (r TypeSafeResult[T]) UnwrapOrPanic() T

UnwrapOrPanic returns the value or panics if there's an error Use this only when you're certain the operation succeeded

type UnifiedResourceManager ΒΆ added in v1.0.6

type UnifiedResourceManager struct {
	// contains filtered or unexported fields
}

UnifiedResourceManager consolidates all resource management for optimal performance sync.Pool is inherently thread-safe, no additional locks needed for pool operations

func NewUnifiedResourceManager ΒΆ added in v1.0.6

func NewUnifiedResourceManager() *UnifiedResourceManager

NewUnifiedResourceManager creates a new unified resource manager

func (*UnifiedResourceManager) GetBuffer ΒΆ added in v1.0.6

func (urm *UnifiedResourceManager) GetBuffer() []byte

func (*UnifiedResourceManager) GetMap ΒΆ added in v1.2.0

func (urm *UnifiedResourceManager) GetMap() map[string]any

GetMap gets a map from the pool PERFORMANCE: Reusable maps for JSON object operations

func (*UnifiedResourceManager) GetOptions ΒΆ added in v1.2.0

func (urm *UnifiedResourceManager) GetOptions() *ProcessorOptions

GetOptions gets a ProcessorOptions from the pool

func (*UnifiedResourceManager) GetPathSegments ΒΆ added in v1.0.6

func (urm *UnifiedResourceManager) GetPathSegments() []internal.PathSegment

func (*UnifiedResourceManager) GetStats ΒΆ added in v1.0.6

func (*UnifiedResourceManager) GetStringBuilder ΒΆ added in v1.0.6

func (urm *UnifiedResourceManager) GetStringBuilder() *strings.Builder

func (*UnifiedResourceManager) PerformMaintenance ΒΆ added in v1.0.6

func (urm *UnifiedResourceManager) PerformMaintenance()

PerformMaintenance performs periodic cleanup sync.Pool automatically handles cleanup via GC

func (*UnifiedResourceManager) PutBuffer ΒΆ added in v1.0.6

func (urm *UnifiedResourceManager) PutBuffer(buf []byte)

func (*UnifiedResourceManager) PutMap ΒΆ added in v1.2.0

func (urm *UnifiedResourceManager) PutMap(m map[string]any)

PutMap returns a map to the pool

func (*UnifiedResourceManager) PutOptions ΒΆ added in v1.2.0

func (urm *UnifiedResourceManager) PutOptions(opts *ProcessorOptions)

PutOptions returns a ProcessorOptions to the pool

func (*UnifiedResourceManager) PutPathSegments ΒΆ added in v1.0.6

func (urm *UnifiedResourceManager) PutPathSegments(segments []internal.PathSegment)

func (*UnifiedResourceManager) PutStringBuilder ΒΆ added in v1.0.6

func (urm *UnifiedResourceManager) PutStringBuilder(sb *strings.Builder)

type UnmarshalTypeError ΒΆ

type UnmarshalTypeError struct {
	Value  string       // description of JSON value - "bool", "array", "number -5"
	Type   reflect.Type // type of Go value it could not be assigned to
	Offset int64        // error occurred after reading Offset bytes
	Struct string       // name of the root type containing the field
	Field  string       // the full path from root node to the value
	Err    error        // may be nil
}

UnmarshalTypeError describes a JSON value that was not appropriate for a value of a specific Go type.

func (*UnmarshalTypeError) Error ΒΆ

func (e *UnmarshalTypeError) Error() string

func (*UnmarshalTypeError) Unwrap ΒΆ

func (e *UnmarshalTypeError) Unwrap() error

type Unmarshaler ΒΆ

type Unmarshaler interface {
	UnmarshalJSON([]byte) error
}

Unmarshaler is the interface implemented by types that can unmarshal a JSON description of themselves. The input can be assumed to be a valid encoding of a JSON value. UnmarshalJSON must copy the JSON data if it wishes to retain the data after returning.

By convention, to approximate the behavior of Unmarshal itself, Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op.

type UnsupportedTypeError ΒΆ

type UnsupportedTypeError struct {
	Type reflect.Type
}

UnsupportedTypeError is returned by Marshal when attempting to encode an unsupported value type.

func (*UnsupportedTypeError) Error ΒΆ

func (e *UnsupportedTypeError) Error() string

type UnsupportedValueError ΒΆ

type UnsupportedValueError struct {
	Value reflect.Value
	Str   string
}

UnsupportedValueError is returned by Marshal when attempting to encode an unsupported value.

func (*UnsupportedValueError) Error ΒΆ

func (e *UnsupportedValueError) Error() string

type ValidationError ΒΆ

type ValidationError struct {
	Path    string `json:"path"`
	Message string `json:"message"`
}

ValidationError represents a schema validation error

func ValidateSchema ΒΆ

func ValidateSchema(jsonStr string, schema *Schema, opts ...*ProcessorOptions) ([]ValidationError, error)

ValidateSchema validates JSON data against a schema

func (*ValidationError) Error ΒΆ

func (ve *ValidationError) Error() string

type WarmupResult ΒΆ

type WarmupResult struct {
	TotalPaths  int      `json:"total_paths"`
	Successful  int      `json:"successful"`
	Failed      int      `json:"failed"`
	SuccessRate float64  `json:"success_rate"`
	FailedPaths []string `json:"failed_paths,omitempty"`
}

WarmupResult represents the result of a cache warmup operation

func WarmupCache ΒΆ added in v1.1.0

func WarmupCache(jsonStr string, paths []string, opts ...*ProcessorOptions) (*WarmupResult, error)

WarmupCache pre-warms the cache for frequently accessed paths. This can improve performance for subsequent operations on the same JSON.

Directories ΒΆ

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL