Skip to content

JSON Library ​

github.com/cybergodev/json is a Go JSON library for parsing, path queries, modification, validation, formatting, and streaming of large files and JSONL. Function signatures match encoding/json, so existing code compiles after swapping the import; input is validated by default, which introduces a few behavioral differences from the standard library (see Comparison with the Standard Library).

Core Features ​

  • Signature-compatible with encoding/json — Marshal/Unmarshal/Valid/Compact/Indent and the Encoder/Decoder methods share names and signatures with the standard library; swapping the import is enough to compile. Default input validation introduces a few behavioral differences.
  • Thread-safe — one Processor can be shared across goroutines; every public method is protected internally.
  • Path queries — dot notation, array indices, slices, wildcards, and JSON Pointer each express a lookup in one path string.
  • Type-safe access — GetTyped[T] for generic decoding; SafeGet returns an AccessResult you can chain conversions on.
  • Streaming — StreamIterator/StreamObjectIterator decode element by element; the JSONL family processes line by line.
  • Security — input size, nesting depth, invalid UTF-8, and dangerous patterns are validated by default.
  • Caching — parse and result caches are on by default; WarmupCache pre-fills hot paths.
  • Extensible — Hook intercepts Get/Set/Delete; custom encoding goes through MarshalJSON, MarshalText, or CustomEscapes.

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, MarshalIndentOutput bytes match the standard library (typical values)
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, read caps
Extension InterfacesHooks intercept the full Get/Set/Delete flow; custom encoding via MarshalJSON, MarshalText, or CustomEscapes
SecurityInput validation on by default (size/depth/UTF-8/dangerous patterns); SecurityConfig() preset for untrusted input, with a production checklist
ExamplesRunnable examples for paths, codecs, iteration, and JSONL
Advanced ExamplesBatch encoding, field selection, pre-parsing, compiled paths, cache warm-up

Performance Characteristics ​

  • Zero-allocation fast paths — cache keys are comparable structs, so no string is concatenated per operation; with the cache off, single-key property access reads the root object directly and bypasses the recursive processor
  • Caching — parse results and query results are cached by default (EnableCache/CacheResults); WarmupCache pre-fills hot paths
  • Object pools — IterableValue, encoder buffers, and sorted-key slices are reused to reduce GC pressure
  • Parallel streaming — JSONL streaming supports multiple parallel workers (StreamJSONLParallel)
  • Pre-parsing — PreParse parses one JSON document once and shares the parse tree across paths

Comparison with the Standard Library ​

Featureencoding/jsoncybergodev/json
Basic encoding/decoding✅✅ same signatures, plus default input validation
Path queries❌✅ dot/bracket syntax
Type-safe access❌✅ generic API
Streamingbasic streaming decoder✅ element/line iterators
JSONL support❌✅ native support
Security validation❌✅ on by default
Hook system❌✅ extensible
Cache optimization❌✅ parse and result caches

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 ​