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
- Variables
- func ClampIndex(index, length int) int
- func ClearCache()
- func ClearKeyInternCache()
- func Compact(dst *bytes.Buffer, src []byte) error
- func CompactBuffer(dst *bytes.Buffer, src []byte, opts ...*ProcessorOptions) error
- func CompactString(jsonStr string, opts ...*ProcessorOptions) (string, error)
- func CompareJson(json1, json2 string) (bool, error)
- func ConvertFromScientific(s string) (string, error)
- func ConvertToBool(value any) (bool, bool)
- func ConvertToFloat64(value any) (float64, bool)
- func ConvertToInt(value any) (int, bool)
- func ConvertToInt64(value any) (int64, bool)
- func ConvertToString(value any) string
- func ConvertToUint64(value any) (uint64, bool)
- func CreateEmptyContainer(containerType string) any
- func DeepCopy(data any) (any, error)
- func Delete(jsonStr, path string, opts ...*ProcessorOptions) (string, error)
- func DeleteWithCleanNull(jsonStr, path string, opts ...*ProcessorOptions) (string, error)
- func Encode(value any, config ...*EncodeConfig) (string, error)
- func EncodeBatch(pairs map[string]any, pretty bool, opts ...*ProcessorOptions) (string, error)
- func EncodeFields(value any, fields []string, pretty bool, opts ...*ProcessorOptions) (string, error)
- func EncodePretty(value any, config ...*EncodeConfig) (string, error)
- func EncodeStream(values any, pretty bool, opts ...*ProcessorOptions) (string, error)
- func EncodeWithOptions(value any, config *EncodeConfig, opts ...*ProcessorOptions) (string, error)
- func EscapeJSONPointer(s string) string
- func EstimateArraySize(jsonBytes []byte) int
- func EstimateMapSize(jsonBytes []byte) int
- func FastToBool(value any) (bool, bool)
- func FastToFloat64(value any) (float64, bool)
- func FastToInt(value any) (int, bool)
- func FastToString(value any) (string, bool)
- func FastTypeSwitch[T any](value any) (T, bool)
- func Foreach(jsonStr string, fn func(key any, item *IterableValue))
- func ForeachNested(jsonStr string, fn func(key any, item *IterableValue))
- func ForeachReturn(jsonStr string, fn func(key any, item *IterableValue)) (string, error)
- func ForeachWithPath(jsonStr, path string, fn func(key any, item *IterableValue)) error
- func ForeachWithPathAndControl(jsonStr, path string, fn func(key any, value any) IteratorControl) error
- func FormatCompact(jsonStr string, opts ...*ProcessorOptions) (string, error)deprecated
- func FormatNumber(value any) string
- func FormatPretty(jsonStr string, opts ...*ProcessorOptions) (string, error)
- func Get(jsonStr, path string, opts ...*ProcessorOptions) (any, error)
- func GetArray(jsonStr, path string, opts ...*ProcessorOptions) ([]any, error)
- func GetArrayWithDefault(jsonStr, path string, defaultValue []any, opts ...*ProcessorOptions) []any
- func GetBool(jsonStr, path string, opts ...*ProcessorOptions) (bool, error)
- func GetBoolWithDefault(jsonStr, path string, defaultValue bool, opts ...*ProcessorOptions) bool
- func GetContainerSize(data any) int
- func GetEncodeBuffer() []byte
- func GetErrorSuggestion(err error) string
- func GetFloat64(jsonStr, path string, opts ...*ProcessorOptions) (float64, error)
- func GetFloat64WithDefault(jsonStr, path string, defaultValue float64, opts ...*ProcessorOptions) float64
- func GetInt(jsonStr, path string, opts ...*ProcessorOptions) (int, error)
- func GetIntWithDefault(jsonStr, path string, defaultValue int, opts ...*ProcessorOptions) int
- func GetMultiple(jsonStr string, paths []string, opts ...*ProcessorOptions) (map[string]any, error)
- func GetObject(jsonStr, path string, opts ...*ProcessorOptions) (map[string]any, error)
- func GetObjectWithDefault(jsonStr, path string, defaultValue map[string]any, opts ...*ProcessorOptions) map[string]any
- func GetResultBuffer() *[]byte
- func GetString(jsonStr, path string, opts ...*ProcessorOptions) (string, error)
- func GetStringWithDefault(jsonStr, path, defaultValue string, opts ...*ProcessorOptions) string
- func GetTyped[T any](jsonStr, path string, opts ...*ProcessorOptions) (T, error)
- func GetTypedWithDefault[T any](jsonStr, path string, defaultValue T, opts ...*ProcessorOptions) T
- func GetTypedWithProcessor[T any](processor *Processor, jsonStr, path string, opts ...*ProcessorOptions) (T, error)
- func GetWithDefault(jsonStr, path string, defaultValue any, opts ...*ProcessorOptions) any
- func HTMLEscape(dst *bytes.Buffer, src []byte)
- func HTMLEscapeBuffer(dst *bytes.Buffer, src []byte, opts ...*ProcessorOptions)
- func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error
- func IndentBuffer(dst *bytes.Buffer, src []byte, prefix, indent string, ...) error
- func InternKey(key string) string
- func InternMapKeys(m map[string]any)
- func IsContainer(data any) bool
- func IsInteger(s string) bool
- func IsLargeNumber(numStr string) bool
- func IsNumeric(s string) bool
- func IsRetryable(err error) bool
- func IsScientificNotation(s string) bool
- func IsSecurityRelated(err error) bool
- func IsUserError(err error) bool
- func IsValidJSON(jsonStr string) bool
- func IsValidPath(path string) bool
- func KeyInternCacheSize() int
- func LoadFromFile(filePath string, opts ...*ProcessorOptions) (string, error)
- func Marshal(v any) ([]byte, error)
- func MarshalIndent(v any, prefix, indent string) ([]byte, error)
- func MarshalToFile(path string, data any, pretty ...bool) error
- func MergeJson(json1, json2 string) (string, error)
- func NewMapWithEstimatedSize(jsonBytes []byte) map[string]any
- func NewProcessorUtils() *processorUtils
- func NewSliceWithEstimatedSize(jsonBytes []byte) []any
- func ParseArrayIndexGlobal(indexStr string) intdeprecated
- func ParseBool(s string) (bool, error)
- func ParseFloat(s string) (float64, error)
- func ParseInt(s string) (int, error)
- func ParseJSONL(data []byte) ([]any, error)
- func ParseJSONLInto[T any](data []byte) ([]T, error)
- func PreservingUnmarshal(data []byte, v any, preserveNumbers bool) error
- func Print(data any)
- func PrintE(data any) error
- func PrintPretty(data any)
- func PrintPrettyE(data any) error
- func PutEncodeBuffer(buf []byte)
- func PutEncodeConfig(cfg *EncodeConfig)
- func PutPooledDecoder(dec *Decoder)
- func PutResultBuffer(buf *[]byte)
- func SafeConvertToInt64(value any) (int64, error)
- func SafeConvertToUint64(value any) (uint64, error)
- func SafeTypeAssert[T any](value any) (T, bool)
- func SanitizeKey(key string) string
- func SaveToFile(filePath string, data any, pretty ...bool) error
- func Set(jsonStr, path string, value any, opts ...*ProcessorOptions) (string, error)
- func SetGlobalProcessor(processor *Processor)
- func SetMultiple(jsonStr string, updates map[string]any, opts ...*ProcessorOptions) (string, error)
- func SetMultipleWithAdd(jsonStr string, updates map[string]any, opts ...*ProcessorOptions) (string, error)
- func SetWithAdd(jsonStr, path string, value any) (string, error)
- func ShutdownGlobalProcessor()
- func SmartNumberConversion(value any) any
- func StreamArrayCount(reader io.Reader) (int, error)
- func StreamArrayFilter(reader io.Reader, predicate func(any) bool) ([]any, error)
- func StreamArrayFirst(reader io.Reader, predicate func(any) bool) (any, bool, error)
- func StreamArrayForEach(reader io.Reader, fn func(int, any) error) error
- func StreamArrayMap(reader io.Reader, transform func(any) any) ([]any, error)
- func StreamArrayReduce(reader io.Reader, initial any, reducer func(any, any) any) (any, error)
- func StreamArraySkip(reader io.Reader, n int) ([]any, error)
- func StreamArrayTake(reader io.Reader, n int) ([]any, error)
- func StreamLinesInto[T any](reader io.Reader, fn func(lineNum int, data T) error) ([]T, error)
- func StreamLinesIntoWithConfig[T any](reader io.Reader, config JSONLConfig, fn func(lineNum int, data T) error) ([]T, error)
- func TestProcessorResourcePools(processor *Processor) bool
- func ToJSONL(data []any) ([]byte, error)
- func ToJSONLString(data []any) (string, error)
- func TypeSafeConvert[T any](value any) (T, error)
- func UnescapeJSONPointer(s string) string
- func UnifiedTypeConversion[T any](value any) (T, bool)
- func Unmarshal(data []byte, v any) error
- func UnmarshalFromFile(path string, v any, opts ...*ProcessorOptions) error
- func Valid(data []byte) bool
- func ValidString(jsonStr string) bool
- func ValidWithOptions(jsonStr string, opts ...*ProcessorOptions) (bool, error)
- func ValidateConfig(config *Config) error
- func ValidateOptions(options *ProcessorOptions) error
- func ValidatePath(path string) error
- func WarmupPathCache(commonPaths []string)
- func WarmupPathCacheWithProcessor(processor *Processor, commonPaths []string)
- func WrapError(err error, op, message string) error
- func WrapPathError(err error, op, path, message string) error
- type ArrayExtensionError
- type ArrayExtensionNeededError
- type ArrayHelper
- func (ah *ArrayHelper) ClampIndex(index, length int) int
- func (ah *ArrayHelper) CompactArray(arr []any) []any
- func (ah *ArrayHelper) ExtendArray(arr []any, targetLength int) []any
- func (ah *ArrayHelper) GetElement(arr []any, index int) (any, bool)
- func (ah *ArrayHelper) NormalizeIndex(index, length int) int
- func (ah *ArrayHelper) ParseArrayIndex(indexStr string) int
- func (ah *ArrayHelper) PerformSlice(arr []any, start, end, step int) []any
- func (ah *ArrayHelper) SetElement(arr []any, index int, value any) bool
- func (ah *ArrayHelper) ValidateBounds(index, length int) bool
- type BatchIterator
- type BatchOperation
- type BatchResult
- type BenchmarkHelper
- type BulkProcessor
- type CacheKey
- type CacheStats
- type CheckResult
- type ChunkedReader
- type ChunkedWriter
- type ConcurrencyTester
- type Config
- func (c *Config) Clone() *Config
- func (c *Config) GetCacheTTL() time.Duration
- func (c *Config) GetMaxCacheSize() int
- func (c *Config) GetMaxConcurrency() int
- func (c *Config) GetMaxJSONSize() int64
- func (c *Config) GetMaxNestingDepth() int
- func (c *Config) GetMaxPathDepth() int
- func (c *Config) GetSecurityLimits() map[string]any
- func (c *Config) IsCacheEnabled() bool
- func (c *Config) IsCommentsAllowed() bool
- func (c *Config) IsHealthCheckEnabled() bool
- func (c *Config) IsMetricsEnabled() bool
- func (c *Config) IsStrictMode() bool
- func (c *Config) ShouldCleanupNulls() bool
- func (c *Config) ShouldCompactArrays() bool
- func (c *Config) ShouldCreatePaths() bool
- func (c *Config) ShouldPreserveNumbers() bool
- func (c *Config) ShouldValidateFilePath() bool
- func (c *Config) ShouldValidateInput() bool
- func (c *Config) Validate() error
- type ConfigInterface
- type CustomEncoder
- type Decoder
- type Delim
- type DetailedStats
- type EncodeConfig
- type Encoder
- type ExtractionContext
- type ExtractionGroup
- type HealthStatus
- type InvalidUnmarshalError
- type IterableValue
- func (iv *IterableValue) Exists(key string) bool
- func (iv *IterableValue) ForeachNested(path string, fn func(key any, item *IterableValue))
- func (iv *IterableValue) Get(path string) any
- func (iv *IterableValue) GetArray(key string) []any
- func (iv *IterableValue) GetBool(key string) bool
- func (iv *IterableValue) GetBoolWithDefault(key string, defaultValue bool) bool
- func (iv *IterableValue) GetData() any
- func (iv *IterableValue) GetFloat64(key string) float64
- func (iv *IterableValue) GetFloat64WithDefault(key string, defaultValue float64) float64
- func (iv *IterableValue) GetInt(key string) int
- func (iv *IterableValue) GetIntWithDefault(key string, defaultValue int) int
- func (iv *IterableValue) GetObject(key string) map[string]any
- func (iv *IterableValue) GetString(key string) string
- func (iv *IterableValue) GetStringWithDefault(key string, defaultValue string) string
- func (iv *IterableValue) GetWithDefault(key string, defaultValue any) any
- func (iv *IterableValue) IsEmpty(key string) bool
- func (iv *IterableValue) IsEmptyData() bool
- func (iv *IterableValue) IsNull(key string) bool
- func (iv *IterableValue) IsNullData() bool
- func (iv *IterableValue) Release()
- type Iterator
- type IteratorControl
- type JSONLConfig
- type JSONLProcessor
- func (j *JSONLProcessor) Err() error
- func (j *JSONLProcessor) GetStats() JSONLStats
- func (j *JSONLProcessor) Release()
- func (j *JSONLProcessor) Stop()
- func (j *JSONLProcessor) StreamLines(fn func(lineNum int, data any) bool) error
- func (j *JSONLProcessor) StreamLinesParallel(fn func(lineNum int, data any) error, workers int) error
- type JSONLStats
- type JSONLWriter
- type JsonsError
- type LargeFileConfig
- type LargeFileProcessor
- type LazyJSON
- type LazyJSONDecoder
- type LazyParser
- func (lp *LazyParser) Get(path string) (any, error)
- func (lp *LazyParser) GetAll() (map[string]any, error)
- func (lp *LazyParser) GetValue() (any, error)
- func (lp *LazyParser) IsArray() bool
- func (lp *LazyParser) IsObject() bool
- func (lp *LazyParser) IsParsed() bool
- func (lp *LazyParser) Raw() []byte
- type Marshaler
- type MarshalerError
- type MemoryTracker
- type NDJSONProcessor
- type Number
- type NumberPreservingDecoder
- type Operation
- type OperationContext
- type ParallelIterator
- func (it *ParallelIterator) Filter(predicate func(int, any) bool) []any
- func (it *ParallelIterator) ForEach(fn func(int, any) error) error
- func (it *ParallelIterator) ForEachBatch(batchSize int, fn func(int, []any) error) error
- func (it *ParallelIterator) Map(transform func(int, any) (any, error)) ([]any, error)
- type ParsedJSON
- type PathInfo
- type PathSegment
- type PathType
- type PooledMapIterator
- type PooledSliceIterator
- type Processor
- func (p *Processor) BatchDeleteOptimized(jsonStr string, paths []string) (string, error)
- func (p *Processor) BatchSetOptimized(jsonStr string, updates map[string]any) (string, error)
- func (p *Processor) ClearCache()
- func (p *Processor) Close() error
- func (p *Processor) Compact(jsonStr string, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) CompactBuffer(dst *bytes.Buffer, src []byte, opts ...*ProcessorOptions) error
- func (p *Processor) CompilePath(path string) (*internal.CompiledPath, error)
- func (p *Processor) Delete(jsonStr, path string, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) DeleteWithCleanNull(jsonStr, path string, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) Encode(value any, config ...*EncodeConfig) (string, error)
- func (p *Processor) EncodeBatch(pairs map[string]any, pretty bool, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) EncodeFields(value any, fields []string, pretty bool, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) EncodePretty(value any, config ...*EncodeConfig) (string, error)
- func (p *Processor) EncodeStream(values any, pretty bool, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) EncodeStreamWithOptions(values any, encOpts *EncodeConfig, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) EncodeWithConfig(value any, config *EncodeConfig, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) EncodeWithOptions(value any, encOpts *EncodeConfig, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) FastDelete(jsonStr, path string) (string, error)
- func (p *Processor) FastGetMultiple(jsonStr string, paths []string) (map[string]any, error)
- func (p *Processor) FastSet(jsonStr, path string, value any) (string, error)
- func (p *Processor) Foreach(jsonStr string, fn func(key any, item *IterableValue))
- func (p *Processor) ForeachNested(jsonStr string, fn func(key any, item *IterableValue))
- func (p *Processor) ForeachReturn(jsonStr string, fn func(key any, item *IterableValue)) (string, error)
- func (p *Processor) ForeachWithPath(jsonStr, path string, fn func(key any, item *IterableValue)) error
- func (p *Processor) ForeachWithPathAndControl(jsonStr, path string, fn func(key any, value any) IteratorControl) error
- func (p *Processor) ForeachWithPathAndIterator(jsonStr, path string, ...) error
- func (p *Processor) FormatCompact(jsonStr string, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) FormatPretty(jsonStr string, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) Get(jsonStr, path string, opts ...*ProcessorOptions) (any, error)
- func (p *Processor) GetArray(jsonStr, path string, opts ...*ProcessorOptions) ([]any, error)
- func (p *Processor) GetArrayWithDefault(jsonStr, path string, defaultValue []any, opts ...*ProcessorOptions) []any
- func (p *Processor) GetBool(jsonStr, path string, opts ...*ProcessorOptions) (bool, error)
- func (p *Processor) GetBoolWithDefault(jsonStr, path string, defaultValue bool, opts ...*ProcessorOptions) bool
- func (p *Processor) GetCompiled(jsonStr string, cp *internal.CompiledPath) (any, error)
- func (p *Processor) GetCompiledExists(data any, cp *internal.CompiledPath) bool
- func (p *Processor) GetCompiledFromParsed(data any, cp *internal.CompiledPath) (any, error)
- func (p *Processor) GetConfig() *Config
- func (p *Processor) GetFloat64(jsonStr, path string, opts ...*ProcessorOptions) (float64, error)
- func (p *Processor) GetFloat64WithDefault(jsonStr, path string, defaultValue float64, opts ...*ProcessorOptions) float64
- func (p *Processor) GetFromParsed(parsed *ParsedJSON, path string, opts ...*ProcessorOptions) (any, error)
- func (p *Processor) GetFromParsedData(data any, path string) (any, error)
- func (p *Processor) GetHealthStatus() HealthStatus
- func (p *Processor) GetInt(jsonStr, path string, opts ...*ProcessorOptions) (int, error)
- func (p *Processor) GetIntWithDefault(jsonStr, path string, defaultValue int, opts ...*ProcessorOptions) int
- func (p *Processor) GetMultiple(jsonStr string, paths []string, opts ...*ProcessorOptions) (map[string]any, error)
- func (p *Processor) GetObject(jsonStr, path string, opts ...*ProcessorOptions) (map[string]any, error)
- func (p *Processor) GetObjectWithDefault(jsonStr, path string, defaultValue map[string]any, opts ...*ProcessorOptions) map[string]any
- func (p *Processor) GetStats() Stats
- func (p *Processor) GetString(jsonStr, path string, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) GetStringWithDefault(jsonStr, path, defaultValue string, opts ...*ProcessorOptions) string
- func (p *Processor) GetWithDefault(jsonStr, path string, defaultValue any, opts ...*ProcessorOptions) any
- func (p *Processor) HTMLEscapeBuffer(dst *bytes.Buffer, src []byte, opts ...*ProcessorOptions)
- func (p *Processor) IndentBuffer(dst *bytes.Buffer, src []byte, prefix, indent string, ...) error
- func (p *Processor) IsClosed() bool
- func (p *Processor) LoadFromFile(filePath string, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) LoadFromFileAsData(filePath string, opts ...*ProcessorOptions) (any, error)
- func (p *Processor) LoadFromReader(reader io.Reader, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) LoadFromReaderAsData(reader io.Reader, opts ...*ProcessorOptions) (any, error)
- func (p *Processor) Marshal(value any, opts ...*ProcessorOptions) ([]byte, error)
- func (p *Processor) MarshalIndent(value any, prefix, indent string, opts ...*ProcessorOptions) ([]byte, error)
- func (p *Processor) MarshalToFile(path string, data any, pretty ...bool) error
- func (p *Processor) Parse(jsonStr string, target any, opts ...*ProcessorOptions) error
- func (p *Processor) PreParse(jsonStr string, opts ...*ProcessorOptions) (*ParsedJSON, error)
- func (p *Processor) ProcessBatch(operations []BatchOperation, opts ...*ProcessorOptions) ([]BatchResult, error)
- func (p *Processor) SafeGet(jsonStr, path string) TypeSafeAccessResult
- func (p *Processor) SaveToFile(filePath string, data any, pretty ...bool) error
- func (p *Processor) SaveToWriter(writer io.Writer, data any, pretty bool, opts ...*ProcessorOptions) error
- func (p *Processor) Set(jsonStr, path string, value any, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) SetFromParsed(parsed *ParsedJSON, path string, value any, opts ...*ProcessorOptions) (*ParsedJSON, error)
- func (p *Processor) SetLogger(logger *slog.Logger)
- func (p *Processor) SetMultiple(jsonStr string, updates map[string]any, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) SetMultipleWithAdd(jsonStr string, updates map[string]any, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) SetWithAdd(jsonStr, path string, value any, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) ToJsonString(value any, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) ToJsonStringPretty(value any, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) ToJsonStringStandard(value any, opts ...*ProcessorOptions) (string, error)
- func (p *Processor) Unmarshal(data []byte, v any, opts ...*ProcessorOptions) error
- func (p *Processor) UnmarshalFromFile(path string, v any, opts ...*ProcessorOptions) error
- func (p *Processor) Valid(jsonStr string, opts ...*ProcessorOptions) (bool, error)
- func (p *Processor) ValidBytes(data []byte) bool
- func (p *Processor) ValidateSchema(jsonStr string, schema *Schema, opts ...*ProcessorOptions) ([]ValidationError, error)
- func (p *Processor) WarmupCache(jsonStr string, paths []string, opts ...*ProcessorOptions) (*WarmupResult, error)
- type ProcessorMetrics
- type ProcessorOptions
- type PropertyAccessResult
- type RecursiveProcessor
- type ResourceManagerStats
- type ResourceMonitor
- func (rm *ResourceMonitor) CheckForLeaks() []string
- func (rm *ResourceMonitor) GetMemoryEfficiency() float64
- func (rm *ResourceMonitor) GetPoolEfficiency() float64
- func (rm *ResourceMonitor) GetStats() ResourceStats
- func (rm *ResourceMonitor) RecordAllocation(bytes int64)
- func (rm *ResourceMonitor) RecordDeallocation(bytes int64)
- func (rm *ResourceMonitor) RecordOperation(duration time.Duration)
- func (rm *ResourceMonitor) RecordPoolEviction()
- func (rm *ResourceMonitor) RecordPoolHit()
- func (rm *ResourceMonitor) RecordPoolMiss()
- func (rm *ResourceMonitor) Reset()
- type ResourcePoolStats
- type ResourceStats
- type RootDataTypeConversionError
- type SamplingReader
- type Schema
- func (s *Schema) HasMaxItems() bool
- func (s *Schema) HasMaxLength() bool
- func (s *Schema) HasMaximum() bool
- func (s *Schema) HasMinItems() bool
- func (s *Schema) HasMinLength() bool
- func (s *Schema) HasMinimum() bool
- func (s *Schema) SetExclusiveMaximum(exclusive bool) *Schema
- func (s *Schema) SetExclusiveMinimum(exclusive bool) *Schema
- func (s *Schema) SetMaxItems(maxItems int) *Schema
- func (s *Schema) SetMaxLength(maxLength int) *Schema
- func (s *Schema) SetMaximum(maximum float64) *Schema
- func (s *Schema) SetMinItems(minItems int) *Schema
- func (s *Schema) SetMinLength(minLength int) *Schema
- func (s *Schema) SetMinimum(minimum float64) *Schema
- type SecurityValidator
- type ShardStats
- type Stats
- type StreamIterator
- type StreamIteratorConfig
- type StreamObjectIterator
- type StreamingProcessor
- func (sp *StreamingProcessor) GetStats() StreamingStats
- func (sp *StreamingProcessor) StreamArray(fn func(index int, item any) bool) error
- func (sp *StreamingProcessor) StreamArrayChunked(chunkSize int, fn func([]any) error) error
- func (sp *StreamingProcessor) StreamObject(fn func(key string, value any) bool) error
- func (sp *StreamingProcessor) StreamObjectChunked(chunkSize int, fn func(map[string]any) error) error
- type StreamingStats
- type SyntaxError
- type TestDataGenerator
- type TestHelper
- func (h *TestHelper) AssertEqual(expected, actual any, msgAndArgs ...any)
- func (h *TestHelper) AssertError(err error, msgAndArgs ...any)
- func (h *TestHelper) AssertErrorContains(err error, contains string, msgAndArgs ...any)
- func (h *TestHelper) AssertFalse(condition bool, msgAndArgs ...any)
- func (h *TestHelper) AssertNil(value any, msgAndArgs ...any)
- func (h *TestHelper) AssertNoError(err error, msgAndArgs ...any)
- func (h *TestHelper) AssertNoPanic(fn func(), msgAndArgs ...any)
- func (h *TestHelper) AssertNotEqual(expected, actual any, msgAndArgs ...any)
- func (h *TestHelper) AssertNotNil(value any, msgAndArgs ...any)
- func (h *TestHelper) AssertPanic(fn func(), msgAndArgs ...any)
- func (h *TestHelper) AssertTrue(condition bool, msgAndArgs ...any)
- type TextMarshaler
- type TextUnmarshaler
- type Token
- type TypeSafeAccessResult
- type TypeSafeResult
- type UnifiedResourceManager
- func (urm *UnifiedResourceManager) GetBuffer() []byte
- func (urm *UnifiedResourceManager) GetMap() map[string]any
- func (urm *UnifiedResourceManager) GetOptions() *ProcessorOptions
- func (urm *UnifiedResourceManager) GetPathSegments() []internal.PathSegment
- func (urm *UnifiedResourceManager) GetStats() ResourceManagerStats
- func (urm *UnifiedResourceManager) GetStringBuilder() *strings.Builder
- func (urm *UnifiedResourceManager) PerformMaintenance()
- func (urm *UnifiedResourceManager) PutBuffer(buf []byte)
- func (urm *UnifiedResourceManager) PutMap(m map[string]any)
- func (urm *UnifiedResourceManager) PutOptions(opts *ProcessorOptions)
- func (urm *UnifiedResourceManager) PutPathSegments(segments []internal.PathSegment)
- func (urm *UnifiedResourceManager) PutStringBuilder(sb *strings.Builder)
- type UnmarshalTypeError
- type Unmarshaler
- type UnsupportedTypeError
- type UnsupportedValueError
- type ValidationError
- type WarmupResult
Constants ΒΆ
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.
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 ΒΆ
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.
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 ΒΆ
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 ΒΆ
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 ΒΆ
CompareJson compares two JSON strings for equality
func ConvertFromScientific ΒΆ
ConvertFromScientific converts a scientific notation string to regular number format
func ConvertToBool ΒΆ added in v1.0.4
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
ConvertToFloat64 converts any value to float64 REFACTORED: Uses internal core function to reduce code duplication
func ConvertToInt ΒΆ added in v1.0.4
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
ConvertToInt64 converts any value to int64 REFACTORED: Uses internal core function to reduce code duplication
func ConvertToString ΒΆ added in v1.0.4
ConvertToString converts any value to string (for backward compatibility)
func ConvertToUint64 ΒΆ added in v1.0.4
ConvertToUint64 converts any value to uint64 REFACTORED: Uses internal core function to reduce code duplication
func CreateEmptyContainer ΒΆ
CreateEmptyContainer creates an empty container of the specified type
func DeepCopy ΒΆ
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
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 ΒΆ
EscapeJSONPointer escapes special characters for JSON Pointer
func EstimateArraySize ΒΆ added in v1.2.0
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
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
FastToBool converts any value to bool using optimized type switch PERFORMANCE: Avoids reflection for common types
func FastToFloat64 ΒΆ added in v1.2.0
FastToFloat64 converts any value to float64 using optimized type switch PERFORMANCE: Avoids reflection for common types
func FastToInt ΒΆ added in v1.2.0
FastToInt converts any value to int using optimized type switch PERFORMANCE: Avoids reflection for common types
func FastToString ΒΆ added in v1.2.0
FastToString converts any value to string using optimized type switch PERFORMANCE: Avoids reflection for common types
func FastTypeSwitch ΒΆ added in v1.2.0
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 ΒΆ
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 ΒΆ
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
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 ΒΆ
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 ΒΆ
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 ΒΆ
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
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
InternMapKeys interns all keys in a map PERFORMANCE: Reduces memory usage when the same keys appear in multiple maps
func IsContainer ΒΆ
IsContainer checks if the data is a container type (map or slice)
func IsLargeNumber ΒΆ
IsLargeNumber checks if a string represents a number that's too large for standard numeric types
func IsRetryable ΒΆ added in v1.0.10
IsRetryable determines if an error is retryable
func IsScientificNotation ΒΆ
IsScientificNotation checks if a string represents a number in scientific notation
func IsSecurityRelated ΒΆ added in v1.0.10
IsSecurityRelated determines if an error is security-related
func IsUserError ΒΆ added in v1.0.10
IsUserError determines if an error is caused by user input
func IsValidJSON ΒΆ added in v1.0.10
IsValidJSON quickly checks if a string is valid JSON
func IsValidPath ΒΆ
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 ΒΆ
Marshal returns the JSON encoding of v. This function is 100% compatible with encoding/json.Marshal.
func MarshalIndent ΒΆ
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
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 ΒΆ
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
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
NewSliceWithEstimatedSize creates a new slice with capacity estimated from JSON bytes
func ParseArrayIndexGlobal
deprecated
added in
v1.0.7
func ParseFloat ΒΆ
ParseFloat parses a string to float64 with error handling
func ParseJSONL ΒΆ added in v1.2.0
ParseJSONL parses JSONL data from a byte slice
func ParseJSONLInto ΒΆ added in v1.2.0
ParseJSONLInto parses JSONL data into typed values
func PreservingUnmarshal ΒΆ
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
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
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 ΒΆ
SafeConvertToInt64 safely converts any value to int64 with error handling
func SafeConvertToUint64 ΒΆ
SafeConvertToUint64 safely converts any value to uint64 with error handling
func SafeTypeAssert ΒΆ
SafeTypeAssert performs a safe type assertion with generics
func SanitizeKey ΒΆ
SanitizeKey sanitizes a key for safe use in maps
func SaveToFile ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
SmartNumberConversion provides intelligent number type conversion
func StreamArrayCount ΒΆ added in v1.2.0
StreamArrayCount counts elements without storing them Memory-efficient for just getting array length
func StreamArrayFilter ΒΆ added in v1.2.0
StreamArrayFilter filters array elements during streaming Only elements that pass the predicate are kept
func StreamArrayFirst ΒΆ added in v1.2.0
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
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
StreamArrayMap transforms array elements during streaming Each element is transformed using the provided function
func StreamArrayReduce ΒΆ added in v1.2.0
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
StreamArraySkip skips the first n elements and returns the rest Useful for pagination
func StreamArrayTake ΒΆ added in v1.2.0
StreamArrayTake returns the first n elements from a streaming array Useful for pagination or sampling
func StreamLinesInto ΒΆ added in v1.2.0
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 ΒΆ
TestProcessorResourcePools tests processor resource pool functionality
func ToJSONLString ΒΆ added in v1.2.0
ToJSONLString converts a slice of values to JSONL format string
func TypeSafeConvert ΒΆ
TypeSafeConvert attempts to convert a value to the target type safely
func UnescapeJSONPointer ΒΆ
UnescapeJSONPointer unescapes JSON Pointer special characters
func UnifiedTypeConversion ΒΆ added in v1.0.4
UnifiedTypeConversion provides optimized type conversion with comprehensive support
func Unmarshal ΒΆ
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 ΒΆ
Valid reports whether data is valid JSON. This function is 100% compatible with encoding/json.Valid.
func ValidString ΒΆ added in v1.2.2
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 ΒΆ
ValidateConfig validates configuration values and applies corrections
func ValidateOptions ΒΆ
func ValidateOptions(options *ProcessorOptions) error
ValidateOptions validates processor options with enhanced checks
func ValidatePath ΒΆ
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
WarmupPathCacheWithProcessor pre-populates the path cache using a specific processor PERFORMANCE: Useful when using custom processor configurations
func WrapPathError ΒΆ added in v1.0.6
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
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 ΒΆ
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
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 (*Config) GetMaxCacheSize ΒΆ
func (*Config) GetMaxConcurrency ΒΆ
func (*Config) GetMaxJSONSize ΒΆ
func (*Config) GetMaxNestingDepth ΒΆ
func (*Config) GetMaxPathDepth ΒΆ
func (*Config) GetSecurityLimits ΒΆ
GetSecurityLimits returns a summary of current security limits
func (*Config) IsCacheEnabled ΒΆ
ConfigInterface implementation methods
func (*Config) IsCommentsAllowed ΒΆ added in v1.0.10
func (*Config) IsHealthCheckEnabled ΒΆ
func (*Config) IsMetricsEnabled ΒΆ
func (*Config) IsStrictMode ΒΆ
func (*Config) ShouldCleanupNulls ΒΆ
func (*Config) ShouldCompactArrays ΒΆ
func (*Config) ShouldCreatePaths ΒΆ
func (*Config) ShouldPreserveNumbers ΒΆ added in v1.0.10
func (*Config) ShouldValidateFilePath ΒΆ
func (*Config) ShouldValidateInput ΒΆ
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
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
GetPooledDecoder gets a decoder from the global pool PERFORMANCE: Use this for streaming scenarios to reduce allocations
func NewDecoder ΒΆ
NewDecoder returns a new decoder that reads from r. This function is fully compatible with encoding/json.NewDecoder.
func (*Decoder) Decode ΒΆ
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 ΒΆ
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 ΒΆ
NewEncoder returns a new encoder that writes to w. This function is fully compatible with encoding/json.NewEncoder.
func (*Encoder) Encode ΒΆ
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 ΒΆ
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.
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 ΒΆ
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
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
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
NewLazyJSON creates a new LazyJSON from raw bytes
func (*LazyJSON) Get ΒΆ added in v1.2.0
Get retrieves a value at the specified path Parses the JSON on first access
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 ΒΆ
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.
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 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
ForEachBatch processes elements in batches in parallel Each batch is processed by a single goroutine
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
func GetPathType ΒΆ added in v1.2.0
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 ΒΆ
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
BatchDeleteOptimized performs multiple Delete operations efficiently
func (*Processor) BatchSetOptimized ΒΆ added in v1.2.0
BatchSetOptimized performs multiple Set operations efficiently
func (*Processor) Close ΒΆ
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
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
FastDelete is an optimized Delete operation for simple paths
func (*Processor) FastGetMultiple ΒΆ added in v1.2.0
FastGetMultiple performs multiple Get operations with single parse
func (*Processor) FastSet ΒΆ added in v1.2.0
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
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
GetCompiledFromParsed retrieves a value from pre-parsed JSON data using a compiled path PERFORMANCE: No JSON parsing overhead - uses already parsed data
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
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) 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) 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 ΒΆ
LoadFromReader loads JSON data from an io.Reader and returns the raw JSON string.
func (*Processor) LoadFromReaderAsData ΒΆ added in v1.1.0
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
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 ΒΆ
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 ΒΆ
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) 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
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 ΒΆ
RootDataTypeConversionError signals that root data type conversion is needed
func (*RootDataTypeConversionError) Error ΒΆ
func (e *RootDataTypeConversionError) Error() string
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 ΒΆ
HasMaxItems returns true if MaxItems constraint is explicitly set
func (*Schema) HasMaxLength ΒΆ
HasMaxLength returns true if MaxLength constraint is explicitly set
func (*Schema) HasMaximum ΒΆ
HasMaximum returns true if Maximum constraint is explicitly set
func (*Schema) HasMinItems ΒΆ
HasMinItems returns true if MinItems constraint is explicitly set
func (*Schema) HasMinLength ΒΆ
HasMinLength returns true if MinLength constraint is explicitly set
func (*Schema) HasMinimum ΒΆ
HasMinimum returns true if Minimum constraint is explicitly set
func (*Schema) SetExclusiveMaximum ΒΆ
SetExclusiveMaximum sets the exclusive maximum flag
func (*Schema) SetExclusiveMinimum ΒΆ
SetExclusiveMinimum sets the exclusive minimum flag
func (*Schema) SetMaxItems ΒΆ
SetMaxItems sets the maximum items constraint for arrays
func (*Schema) SetMaxLength ΒΆ
SetMaxLength sets the maximum length constraint
func (*Schema) SetMaximum ΒΆ
SetMaximum sets the maximum value constraint
func (*Schema) SetMinItems ΒΆ
SetMinItems sets the minimum items constraint for arrays
func (*Schema) SetMinLength ΒΆ
SetMinLength sets the minimum length constraint
func (*Schema) SetMinimum ΒΆ
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 ΒΆ
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
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
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 ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
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 (urm *UnifiedResourceManager) GetStats() ResourceManagerStats
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 ΒΆ
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 ΒΆ
UnsupportedTypeError is returned by Marshal when attempting to encode an unsupported value type.
func (*UnsupportedTypeError) Error ΒΆ
func (e *UnsupportedTypeError) Error() string
type UnsupportedValueError ΒΆ
UnsupportedValueError is returned by Marshal when attempting to encode an unsupported value.
func (*UnsupportedValueError) Error ΒΆ
func (e *UnsupportedValueError) Error() string
type ValidationError ΒΆ
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.