json

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2025 License: MIT Imports: 6 Imported by: 0

README

json codec for JSON Patch+ patches

json codec implements the nominal human-friendly encoding of JSON Patch+ operations like described JSON Patch specification.

This implementation provides 100% json-joy compatibility with complete TypeScript API matching.

Operations are encoded using JSON objects, for example, add operations:

{"op": "add", "path": "/foo/bar", "value": 123}

Features

  • Complete json-joy compatibility - 100% functional compatibility with TypeScript implementation
  • All 47 operation types supported - JSON Patch (RFC6902) + JSON Predicate + JSON Patch Extended
  • High-performance optimizations - Uses JSON v2 for better type preservation and performance
  • Zero-allocation hot paths - Optimized for common operation patterns
  • Comprehensive TypeScript documentation - Every function includes original TypeScript code references

Usage

Basic Usage
import (
    "github.com/kaptinlin/jsonpatch/codec/json"
)

// Create operations from JSON
patch := []map[string]interface{}{
    {"op": "test", "path": "/foo", "value": "bar"},
    {"op": "replace", "path": "/foo", "value": "baz"},
}

// Configure options (optional)
options := json.JsonPatchOptions{
    CreateMatcher: func(pattern string, ignoreCase bool) json.RegexMatcher {
        // Custom regex matcher implementation
        return func(value string) bool {
            // Your regex matching logic
            return true
        }
    },
}

// Decode to operations
ops, err := json.Decode(patch, options)
if err != nil {
    // handle error
}

// Encode operations to JSON
encoded, err := json.EncodeJSON(ops)
if err != nil {
    // handle error
}

// Decode JSON to operations
decoded, err := json.DecodeJSON(encoded, options)
if err != nil {
    // handle error
}
Using Decoder and Encoder Classes
import (
    "github.com/kaptinlin/jsonpatch/codec/json"
)

// Using Decoder (matches TypeScript Decoder class)
options := json.JsonPatchOptions{}
decoder := json.NewDecoder(options)
ops, err := decoder.Decode(patch)
if err != nil {
    // handle error
}

// Using Encoder (matches TypeScript Encoder class)
encoder := json.NewEncoder()
operations, err := encoder.Encode(ops)
if err != nil {
    // handle error
}

// Encode to JSON bytes
jsonBytes, err := encoder.EncodeJSON(ops)
if err != nil {
    // handle error
}

Supported Operations

This codec supports all JSON Patch+ operations with complete TypeScript compatibility:

Core JSON Patch (RFC 6902)
  • add - Add a value to the document
  • remove - Remove a value from the document
  • replace - Replace a value in the document
  • move - Move a value within the document
  • copy - Copy a value within the document
  • test - Test that a value is as expected
JSON Predicate Operations
  • defined - Test if path exists in document
  • undefined - Test if path does not exist in document
  • contains - Test if string contains substring
  • starts - Test if string starts with prefix
  • ends - Test if string ends with suffix
  • matches - Test if string matches regex pattern (requires CreateMatcher)
  • type - Test value type (string, number, boolean, object, integer, array, null)
  • in - Test if value is in array
  • less - Test if number is less than value
  • more - Test if number is greater than value
  • and - Logical AND of multiple predicates
  • or - Logical OR of multiple predicates
  • not - Logical NOT of multiple predicates
Extended Operations
  • str_ins - Insert string at position
  • str_del - Delete string at position
  • flip - Flip boolean value
  • inc - Increment number value
  • split - Split object at specified position
  • merge - Merge objects
  • extend - Extend object with properties
Additional Test Operations
  • test_type - Test value type with array support
  • test_string - Test string at specific position
  • test_string_len - Test string length

TypeScript Compatibility

This implementation maintains 100% compatibility with the json-joy TypeScript implementation:

  • Identical operation semantics - All operations behave exactly like TypeScript
  • Compatible error handling - Error types and messages match TypeScript
  • Same JSON format - Generated JSON is identical to TypeScript output
  • Matching API design - Function signatures mirror TypeScript interfaces

Performance Optimizations

  • JSON v2 integration - Uses github.com/go-json-experiment/json for better type preservation
  • Pre-allocated slices - Avoids memory reallocations in hot paths
  • Zero-allocation type checking - Fast operation type detection
  • Optimized path handling - Uses github.com/kaptinlin/jsonpointer for efficient JSON Pointer operations
  • Bulk operation processing - Efficient handling of operation arrays

Architecture

The codec follows the layered architecture pattern from rules.md:

codec/json/
├── types.go      # Core type definitions and helpers
├── decode.go     # JSON to Op conversion (matches decode.ts)  
├── encode.go     # Op to JSON conversion (matches encode.ts)
├── decoder.go    # Decoder class (matches Decoder.ts)
├── encoder.go    # Encoder class (matches Encoder.ts)
└── index.go      # Package exports (matches index.ts)

Every function includes complete TypeScript original code references for maintainability and compatibility verification.

Documentation

Overview

Package json implements JSON codec for JSON Patch operations. Provides encoding and decoding functionality for JSON Patch operations with full RFC 6902 support.

Package json implements JSON Patch decoder functionality.

Package json implements JSON codec for JSON Patch operations.

Package json implements JSON Patch encoder functionality.

Package json implements JSON codec for JSON Patch operations. Provides encoding and decoding functionality for JSON Patch operations with full RFC 6902 support.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidPointer            = errors.New("invalid pointer")
	ErrAddOpMissingValue         = errors.New("add operation missing 'value' field")
	ErrReplaceOpMissingValue     = errors.New("replace operation missing 'value' field")
	ErrNotOpRequiresOperand      = errors.New("not operation requires at least one operand")
	ErrMissingValueField         = errors.New("missing value field")
	ErrEmptyTypeList             = errors.New("empty type list")
	ErrInvalidType               = errors.New("invalid type")
	ErrNotOpRequiresValidOperand = errors.New("not operation requires a valid predicate operand")
)

Decode operation errors - define clearly and concisely

View Source
var (
	// Core field validation errors
	ErrOpMissingOpField   = errors.New("operation missing 'op' field")
	ErrOpMissingPathField = errors.New("operation missing 'path' field")

	// Move/Copy operation errors
	ErrMoveOpMissingFrom = errors.New("move operation missing 'from' field")
	ErrCopyOpMissingFrom = errors.New("copy operation missing 'from' field")

	// Extended operation errors
	ErrIncOpMissingInc       = errors.New("inc operation missing 'inc' field")
	ErrStrInsOpMissingPos    = errors.New("str_ins operation missing 'pos' field")
	ErrStrInsOpMissingStr    = errors.New("str_ins operation missing 'str' field")
	ErrStrDelOpMissingPos    = errors.New("str_del operation missing 'pos' field")
	ErrStrDelOpMissingFields = errors.New("str_del operation missing 'str' or 'len' field")
	ErrSplitOpMissingPos     = errors.New("split operation missing 'pos' field")
	ErrMergeOpMissingPos     = errors.New("merge operation missing 'pos' field")

	// Predicate operation errors
	ErrTypeOpMissingValue        = errors.New("type operation missing string 'value' field")
	ErrTestTypeOpMissingType     = errors.New("test_type operation missing 'type' field")
	ErrTestStringOpMissingStr    = errors.New("test_string operation missing 'str' field")
	ErrTestStringLenOpMissingLen = errors.New("test_string_len operation missing 'len' field")
	ErrContainsOpMissingValue    = errors.New("contains operation missing 'value' field")
	ErrEndsOpMissingValue        = errors.New("ends operation missing 'value' field")
	ErrStartsOpMissingValue      = errors.New("starts operation missing 'value' field")
	ErrMatchesOpMissingValue     = errors.New("matches operation missing 'value' field")
	ErrLessOpMissingValue        = errors.New("less operation missing 'value' field")
	ErrMoreOpMissingValue        = errors.New("more operation missing 'value' field")

	// Composite operation errors
	ErrAndOpMissingApply = errors.New("and operation missing 'apply' field")
	ErrOrOpMissingApply  = errors.New("or operation missing 'apply' field")
	ErrNotOpMissingApply = errors.New("not operation missing 'apply' field")

	// Type errors
	ErrValueNotObject = errors.New("value is not an object")

	// Unknown operation error
	ErrCodecOpUnknown = errors.New("unknown operation")
)

Functions

func Decode

func Decode(operations []map[string]interface{}, options internal.JsonPatchOptions) ([]internal.Op, error)

Decode converts JSON operations to Op instances.

func DecodeJSON

func DecodeJSON(data []byte, options internal.JsonPatchOptions) ([]internal.Op, error)

DecodeJSON converts JSON bytes to Op instances.

func Encode

func Encode(ops []internal.Op) ([]map[string]interface{}, error)

Encode converts operations to JSON format.

func EncodeJSON

func EncodeJSON(ops []internal.Op) ([]byte, error)

EncodeJSON converts operations to JSON bytes.

func OperationToOp

func OperationToOp(operation map[string]interface{}, options internal.JsonPatchOptions) (internal.Op, error)

OperationToOp converts JSON operation to Op instance.

func OperationToPredicateOp

func OperationToPredicateOp(operation map[string]interface{}, options internal.JsonPatchOptions) (internal.Op, error)

OperationToPredicateOp converts JSON operation to PredicateOp instance.

Types

type CompactOperation

type CompactOperation = internal.CompactOperation

CompactOperation represents a compact format operation.

type Decoder

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

Decoder provides JSON patch decoding functionality with configurable options.

func NewDecoder

func NewDecoder(options internal.JsonPatchOptions) *Decoder

NewDecoder creates a new Decoder with the given options.

func (*Decoder) Decode

func (d *Decoder) Decode(patch []map[string]interface{}) ([]internal.Op, error)

Decode decodes a JSON patch array to operations using the decoder's options.

type Encoder

type Encoder struct{}

Encoder provides JSON patch encoding functionality.

func NewEncoder

func NewEncoder() *Encoder

NewEncoder creates a new Encoder instance.

func (*Encoder) Encode

func (e *Encoder) Encode(ops []internal.Op) ([]map[string]interface{}, error)

Encode encodes operations to JSON format.

func (*Encoder) EncodeJSON

func (e *Encoder) EncodeJSON(ops []internal.Op) ([]byte, error)

EncodeJSON encodes operations to JSON bytes.

type JsonPatchOptions

type JsonPatchOptions = internal.JsonPatchOptions

JsonPatchOptions contains options for JSON Patch operations.

type Operation

type Operation = internal.Operation

Operation represents a JSON Patch operation in JSON format. This unified structure supports all standard and extended operation internal.

type Options

type Options struct {
	// CreateMatcher creates a regex matcher function for pattern matching operations
	CreateMatcher func(pattern string, ignoreCase bool) func(string) bool
}

Options represents configuration options for JSON codec operations. Provides configurable regex matcher creation for matches operations.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL