Skip to content

JSON Library ​

github.com/cybergodev/json is a high-performance, thread-safe Go JSON processing library. It provides a rich set of JSON operations — parsing, querying, modifying, validating, and formatting — while maintaining 100% compatibility with the standard library encoding/json.

Core Features ​

  • 100% encoding/json compatible — a drop-in replacement for the standard library, no changes to existing code required
  • Thread-safe — all operations are concurrency-safe, suited to high-concurrency workloads
  • Path queries — JSONPath-style path expressions, including wildcards and slices
  • Type-safe access — generic API (GetTyped[T]) and type-assertion methods (SafeGet)
  • Streaming — streaming processing for large files and the JSONL/NDJSON format
  • Security hardening — built-in input validation, depth limits, and dangerous-pattern detection
  • High-performance caching — smart caching, pre-parse optimization, object-pool reuse
  • Extensible — hook system, custom encoders, validators

Installation ​

bash
go get github.com/cybergodev/json

Requires Go 1.25+ (the source go.mod declares go 1.25.0; examples use generics and the slices standard library).

30-Second Quick Tour ​

go
package main

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

func main() {
	data := `{"name": "CyberGo", "version": 1, "tags": ["json", "go"]}`

	// 1. Get by path
	name := json.GetString(data, "name")
	fmt.Println("Name:", name)

	// 2. Modify a value
	updated, _ := json.Set(data, "version", 2)
	fmt.Println("Updated:", updated)

	// 3. Validate
	if json.Valid([]byte(data)) {
		fmt.Println("Valid JSON")
	}

	// 4. Get with a default value
	desc := json.GetString(data, "description", "Default description")
	fmt.Println("Description:", desc)

	// 5. Decode into a struct
	type Config struct {
		Name    string   `json:"name"`
		Version int      `json:"version"`
		Tags    []string `json:"tags"`
	}
	var config Config
	json.Unmarshal([]byte(data), &config)
	fmt.Printf("Config: %+v\n", config)
}

Feature Overview ​

Path Operations ​

FeatureFunctionsDescription
Get valuesGet, GetString, GetInt...Nested paths and array indices supported
Batch getGetMultipleRetrieve values at multiple paths with a single parse
Get with defaultGetString, GetInt, etc.Pass a defaultValue argument
Set valuesSetAutomatically creates missing paths by default (Config.CreatePaths)
Delete valuesDeleteDeletes the specified path

Encoding & Decoding ​

FeatureFunctionsDescription
EncodeMarshal, MarshalIndent100% encoding/json compatible
DecodeUnmarshal, Parse, ParseAnyGenerics and type safety supported
FormatPrettify, CompactJSON pretty-print / compaction

Advanced Features ​

FeatureFunctions/TypesDescription
Generic APIGetTyped[T]Type-safe generic get
Pre-parsingProcessor.PreParse, Processor.GetFromParsedParse once, query many times
Path pre-compilationProcessor.CompilePath, Processor.GetCompiledZero repeated parsing for high-frequency identical paths
Parallel iterationNewParallelIteratorParallel Map/Filter/ForEach with a built-in worker pool
Safe accessSafeGet → AccessResultChained type conversion
StreamingStreamJSONL familyLine-by-line streaming with bounded memory
JSONL processingStreamLinesInto[T]Log/data pipelines
Schema validationValidateSchemaJSON Schema validation

Module Navigation ​

ModuleDescription
Quick StartInstallation, basic usage, core concepts
Path Expression SyntaxPath queries, slices, wildcards, field extraction
Processor GuideWhen to use a Processor, pre-parse optimization, lifecycle
API ReferenceComplete API reference
Large File HandlingItem-by-item file iteration, streaming iterators, memory optimization
Extension InterfacesHook system intercepting the full Get/Set/Delete flow; custom encoding via json.Marshaler/CustomEscapes
SecurityInput validation on by default (size/depth/UTF-8/dangerous patterns); SecurityConfig() preset for untrusted input, with a production checklist
ExamplesReal-world code examples
Advanced ExamplesBatch encoding, pre-parsing, hook system

Performance Characteristics ​

  • Zero-allocation fast paths — single-key access and cache-key building use on-stack buffers to reduce heap allocations
  • Smart caching — hot paths are cached automatically, with cache warm-up support
  • Object pools — reuse of intermediate objects to reduce GC pressure
  • Parallel streaming — JSONL streaming supports multiple parallel workers (StreamJSONLParallel)
  • Pre-parse optimization — parse large JSON once, query many times

Comparison with the Standard Library ​

Featureencoding/jsoncybergodev/json
Basic encoding/decoding✅✅ 100% compatible
Path queries❌✅ dot/bracket syntax
Type-safe access❌✅ generic API
StreamingBasic✅ enhanced
JSONL support❌✅ native support
Security validation❌✅ built-in protection
Hook system❌✅ extensible
Cache optimization❌✅ smart caching

Quick Decision Guide ​

ScenarioRecommended Approach
Simple queryGetString(data, "path")
With a default valueGetString(data, "path", "default")
Type safetyGetTyped[User](data, "user")
Query many paths on one JSONProcessor + PreParse
Query one path across many JSONsProcessor + CompilePath
Large filesStreamIterator (>100MB) / Processor.ForeachFile (10-100MB, fully loaded)
Process large arrays in parallelNewParallelIterator
JSONL pipelinesStreamLinesInto[T]
Untrusted inputSecurityConfig()

Next Steps ​